﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using System.Collections;
using System.Data.SqlClient;
using System.ComponentModel.Design;
using System.IO;
using Srvtools;
using Microsoft.Win32;
using System.Data.Common;
using System.Reflection;
using System.Xml;
using Microsoft.VisualStudio.Designer.Interfaces;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.Design.WebControls;
using System.Globalization;
using System.Resources;
using System.Text.RegularExpressions;
using mshtml;
using InfoRemoteModule;
using System.Web.UI.WebControls;
#if VS90
using WebDevPage = Microsoft.VisualWebDeveloper.Interop.WebDeveloperPage;
using EnvDTE90;
#endif

namespace MWizard
{
	public partial class fmExtEEPWebWizard : Form
	{
#if VS90
        const string REGISTRYNAME = "infolight\\eep.net2008";
#else
        const string REGISTRYNAME = "infolight\\eep.net";
#endif

		private TExtWebClientData FClientData;
		private DTE2 FDTE2;
        private AddIn FAddIn;
        private DbConnection InternalConnection = null;
        private TStringList FAlias;
        private static string _serverPath;
        private string[] FProviderNameList;
        public Boolean SDCall = false;
        private Page FTemplatePage = null;
        private Container FContainer = null;
        private Window FDesignWindow = null;
#if VS90
        private WebDevPage.DesignerDocument FDesignerDocument;
#endif
        private ListViewColumnSorter lvwColumnSorterDataSet;
        private ListViewColumnSorter lvwColumnSorterBindingSource;
        private ListViewColumnSorter lvwColumnSorterFields;

		public fmExtEEPWebWizard()
		{
			InitializeComponent();
            FClientData = new TExtWebClientData(this);
            PrepareWizardService();

            lvwColumnSorterDataSet = new ListViewColumnSorter();
            lvwColumnSorterBindingSource = new ListViewColumnSorter();
            lvwColumnSorterFields = new ListViewColumnSorter();
            this.lvWebDataSet.ListViewItemSorter = lvwColumnSorterDataSet;
            this.lvWebDataSource.ListViewItemSorter = lvwColumnSorterBindingSource;
            this.lvSelectedFields.ListViewItemSorter = lvwColumnSorterFields;
        }

        public fmExtEEPWebWizard(DTE2 aDTE2, AddIn aAddIn)
        {
            InitializeComponent();
            FClientData = new TExtWebClientData(this);
            FDTE2 = aDTE2;
            FAddIn = aAddIn;
            PrepareWizardService();

            lvwColumnSorterDataSet = new ListViewColumnSorter();
            lvwColumnSorterBindingSource = new ListViewColumnSorter();
            lvwColumnSorterFields = new ListViewColumnSorter();
            this.lvWebDataSet.ListViewItemSorter = lvwColumnSorterDataSet;
            this.lvWebDataSource.ListViewItemSorter = lvwColumnSorterBindingSource;
            this.lvSelectedFields.ListViewItemSorter = lvwColumnSorterFields;
        }

        public DbConnection GlobalConnection
        {
            get { return InternalConnection; }
        }

        public String SelectedAlias
        {
            get { return cbEEPAlias.Text; }
        }

        private void PrepareWizardService()
        {
            Show();
            Hide();
        }

        private void ClearValues()
        {
            SDCall = false;
            cbWebSite.Items.Clear();
            cbWebSite.Text = "";
            tbCurrentSolution.Text = FDTE2.Solution.FileName;
            if (tbCurrentSolution.Text != "")
            {
                rbCurrentSolution.Enabled = true;
                rbCurrentSolution.Checked = true;
                rbAddToExistSolution.Checked = false;
                tbSolutionName.Text = "";
                GetWebSite();
            }
            else
            {
                rbCurrentSolution.Enabled = false;
                rbAddToExistSolution.Checked = true;
            }
            tbSolutionName.Text = "";
            cbAddToExistFolder.Items.Clear();
            cbAddToExistFolder.Text = "";
            tbAddToNewFolder.Text = "";
            rbAddToRootFolder_CheckedChanged(rbAddToRootFolder, null);
            tbFormName.Text = "Form1";
            cbWebForm.Text = "WSingle";
            btnAddField.Enabled = false;
            btnDeleteField.Enabled = false;
            FTemplatePage = null;
            ClearFormData();
        }

        private void ClearFormData()
        {
            cbWebDataSource.Enabled = false;
            cbWebDataSource.Items.Clear();
            cbWebDataSource.Items.Add("");
            ClearRefValButton(lvWebDataSet);
            ClearRefValButton(lvWebDataSource);
            ClearRefValButton(lvSelectedFields);
            tvContainer.Nodes.Clear();
            lvWebDataSet.Items.Clear();
            lvWebDataSource.Items.Clear();
            lvSelectedFields.Items.Clear();

            FClientData.Blocks.Clear();
            foreach (InfoDataSet aDataSet in FClientData.DataSetList)
                aDataSet.Dispose();
            FClientData.DataSetList.Clear();
            foreach (InfoBindingSource aBindingSource in FClientData.DataSourceList)
                aBindingSource.Dispose();
            FClientData.DataSourceList.Clear();
            foreach (Component C in FContainer.Components)
                C.Dispose();
        }

        private void Init()
        {
            FContainer = new Container();
            ClearValues();
            LoadDBString();
            if (((FDTE2 != null) && (FDTE2.Solution.FileName != "")) && File.Exists(FDTE2.Solution.FileName))
            {
                EnabledOutputControls();
            }
            RegistryKey key1 = Registry.LocalMachine.OpenSubKey("SOFTWARE\\" + REGISTRYNAME, RegistryKeyPermissionCheck.ReadWriteSubTree);
            if (key1 != null)
            {
                cbEEPAlias.Text = (string)key1.GetValue("WizardConnectionString");
                cbDatabaseType.Text = (string)key1.GetValue("DatabaseType");
                key1.Close();
            }
            DisplayPage(tpConnection);
        }

        private void DisplayPage(TabPage aPage)
        {
            tabControl.TabPages.Clear();
            tabControl.TabPages.Add(aPage);
            tabControl.SelectedTab = aPage;
            EnableButton();
        }

        private void EnableButton()
        {
            btnPrevious.Enabled = tabControl.SelectedTab != tpConnection;
            btnNext.Enabled = tabControl.SelectedTab != tpLayout;
            btnDone.Enabled = tabControl.SelectedTab == tpLayout;
            btnCancel.Enabled = true;
        }

        private void LoadDBString()
        {
            try
            {
                cbEEPAlias.Items.Clear();
                FAlias = new TStringList();
                List<string> list1 = new List<string>();
                string text3 = SystemFile.DBFile;
                XmlDocument document1 = new XmlDocument();
                document1.Load(text3);
                foreach (XmlNode node1 in document1.FirstChild.FirstChild.ChildNodes)
                {
                    list1.Add((string)node1.Name);
                    cbEEPAlias.Items.Add(node1.Name);
                    string text1 = node1.Attributes["String"].Value.Trim();
                    string text2 = WzdUtils.GetPwdString(node1.Attributes["Password"].Value.Trim());
                    if ((text1.Length > 0) && (text2.Length > 0) && text2 != String.Empty)
                    {
                        if (text1[text1.Length - 1] != ';')
                        {
                            text1 = text1 + ";Password=" + text2;
                        }
                        else
                        {
                            text1 = text1 + "Password=" + text2;
                        }
                    }
                    FAlias.AddObject(node1.Name, text1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please setup <DB Manager> of EEPNetServer at first !");
            }
        }

		private void Form1_Load(object sender, EventArgs e)
		{
			// TODO: This line of code loads data into the 'flow7_testDataSet.COLDEF' table. You can move, or remove it, as needed.
            LoadDBString();
		}

        public void ShowWebClientWizard()
        {
            //Show();
            Init();
            ShowDialog();
        }

        public void SDGenWebForm(string XML)
        {
            SDCall = true;
            if (XML != "")
            {
                FClientData.Blocks.Clear();
                FClientData.LoadFromXML(XML);
            }
            TExtWebClientGenerator CG = new TExtWebClientGenerator(FClientData, FDTE2, FAddIn);
            CG.GenWebClientModule();
            SDCall = false;
        }

        private void SetFieldNames(string TableName, System.Windows.Forms.ListView LV, String DataSetName)
	    {
            int I;
            DataRow[] DRs;
            DataRow DR;
            InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
            aInfoCommand.Connection = InternalConnection;
            TableName = WzdUtils.RemoveQuote(TableName, FClientData.DatabaseType);
            aInfoCommand.CommandText = "Select * from COLDEF where TABLE_NAME = '" + TableName + "'";
            IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
            DataSet dsColdef = new DataSet();
            WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, dsColdef, TableName);

            WebDataSet aDataSet = null;
            DataTable dtTableSchema = aDataSet.RealDataSet.Tables[0];
            for (I = 0; I < dtTableSchema.Columns.Count; I++)
            {
                System.Windows.Forms.ListViewItem lvi = new System.Windows.Forms.ListViewItem();
                lvi.Text = dtTableSchema.Columns[I].ColumnName;
                DRs = dsColdef.Tables[0].Select("FIELD_NAME='" + lvi.Text + "'");
                TBlockFieldItem aBlockFieldItem = new TBlockFieldItem();
                aBlockFieldItem.DataField = lvi.Text;
                aBlockFieldItem.DataType = dtTableSchema.Columns[I].DataType;
                lvi.Tag = aBlockFieldItem;
                if (DRs.Length == 1)
                {
                    DR = DRs[0];
                    lvi.SubItems.Add(DR["CAPTION"].ToString());

                    aBlockFieldItem.Description = DR["CAPTION"].ToString();
                    aBlockFieldItem.CheckNull = DR["CHECK_NULL"].ToString().ToUpper();
                    aBlockFieldItem.DefaultValue = DR["DEFAULT_VALUE"].ToString();
                    aBlockFieldItem.ControlType = DR["NEEDBOX"].ToString();
                    aBlockFieldItem.EditMask = DR["EDITMASK"].ToString();
                    aBlockFieldItem.QueryMode = DR["QUERYMODE"].ToString();
                    if (aBlockFieldItem.DataType == typeof(DateTime))
                    {
                        if (aBlockFieldItem.ControlType == null || aBlockFieldItem.ControlType == "")
                            aBlockFieldItem.ControlType = "DateTimeBox";
                    }
                    aBlockFieldItem.QueryMode = DR["QUERYMODE"].ToString();
                }
                LV.Items.Add(lvi);
            }
            /*
    		string[] S = new string[4];
			S[2] = TableName;
            DataTable dtTableSchema = InternalConnection.GetSchema("Columns", S);
            DataRow[] DRs1 = dtTableSchema.Select("", "ORDINAL_POSITION ASC");
            for (I = 0; I < DRs1.Length; I++)
			{
				ListViewItem lvi = new ListViewItem();
				lvi.Text = DRs1[I][3].ToString();
				DRs = dsColdef.Tables[0].Select("FIELD_NAME='" + lvi.Text + "'");
				if (DRs.Length == 1)
				{
					DR = DRs[0];
					lvi.SubItems.Add(DR["CAPTION"].ToString());
				}
				LV.Items.Add(lvi);
			}
             */
	    }

        private void SetFieldNamesByProvider(String TableName, String ProviderName, System.Windows.Forms.ListView aListView)
        {
            if (ProviderName == null || ProviderName.Trim() == "")
                return;

            InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
            aInfoCommand.Connection = InternalConnection;
            TableName = WzdUtils.RemoveQuote(TableName, FClientData.DatabaseType);
            aInfoCommand.CommandText = "Select * from COLDEF where TABLE_NAME = '" + TableName + "'";
            IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
            DataSet dsColdef = new DataSet();
            WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, dsColdef, TableName);

            aListView.Items.Clear();
            WebDataSet aDataSet = new WebDataSet();
            try
            {
                aDataSet.SetWizardDesignMode(true);
                aDataSet.RemoteName = ProviderName;
                aDataSet.AlwaysClose = true;
                aDataSet.Active = true;
                DataTable Table = aDataSet.RealDataSet.Tables[0];
                foreach (DataColumn Column in Table.Columns)
                {
                    System.Windows.Forms.ListViewItem aItem = new System.Windows.Forms.ListViewItem(Column.ColumnName);
                    DataRow[] DRS = dsColdef.Tables[0].Select("FIELD_NAME='" + Column.ColumnName + "'");
                    if (DRS.Length == 1)
                        aItem.SubItems.Add(DRS[0]["CAPTION"].ToString());
                    else
                        aItem.SubItems.Add("");
                    aListView.Items.Add(aItem);
                    TBlockFieldItem aFieldItem = new TBlockFieldItem();
                    aFieldItem.DataField = Column.ColumnName;
                    aFieldItem.DataType = Column.DataType;
                    aItem.Tag = aFieldItem;
                }
            }
            finally
            {
                aDataSet.Dispose();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
		{
            if (tabControl.SelectedTab.Equals(tpConnection))
            {
                RegistryKey key1 = Registry.LocalMachine.OpenSubKey("SOFTWARE\\" + REGISTRYNAME, RegistryKeyPermissionCheck.ReadWriteSubTree);
                if (key1 != null)
                {
                    key1.SetValue("WizardConnectionString", cbEEPAlias.Text);
                    key1.SetValue("DatabaseType", cbDatabaseType.Text);
                    key1.Close();
                }
                string type = FindDBType(cbEEPAlias.Text);
                switch (type)
                {
                    case "1":
                        FClientData.DatabaseType = ClientType.ctMsSql; break;
                    case "2":
                        FClientData.DatabaseType = ClientType.ctOleDB; break;
                    case "3":
                        FClientData.DatabaseType = ClientType.ctOracle; break;
                    case "4":
                        FClientData.DatabaseType = ClientType.ctODBC; break;
                    case "5":
                        FClientData.DatabaseType = ClientType.ctMySql; break;
                    case "6":
                        FClientData.DatabaseType = ClientType.ctInformix; break;
                }

                if (cbWebSite.Items.Count == 1)
                {
                    cbWebSite.SelectedIndex = 0;
                    cbWebSite_SelectedIndexChanged(new object(), new EventArgs());
                }

                if (cbChooseLanguage.Text == "" || cbChooseLanguage.Text == "C#")
                    FClientData.Language = "cs";
                else if (cbChooseLanguage.Text == "VB")
                    FClientData.Language = "vb";
                DisplayPage(tpOutputSetting);
            }
            else if (tabControl.SelectedTab.Equals(tpOutputSetting))
            {
                FClientData.FolderName = "";
                if (rbAddToExistSolution.Checked && tbSolutionName.Text == "")
                {
                    tbSolutionName.Focus();
                    MessageBox.Show("Please input SolutionName");
                }
                else if (cbWebSite.Text == "")
                {
                    cbWebSite.Focus();
                    MessageBox.Show("Please select a WebSite");
                }
                else if (rbAddToExistFolder.Checked && (cbAddToExistFolder.Text == ""))
                {
                    cbAddToExistFolder.Focus();
                    MessageBox.Show("Please select a exist folder");
                }
                else if (rbCurrentSolution.Checked && (tbCurrentSolution.Text == ""))
                {
                    MessageBox.Show("The IDE's Solution is empty");
                }
                else if (rbAddToNewFolder.Checked && (tbAddToNewFolder.Text == ""))
                {
                    tbAddToNewFolder.Focus();
                    MessageBox.Show("Please input new folder");
                }
                else
                {
                    if (rbAddToExistFolder.Checked)
                    {
                        FClientData.FolderName = cbAddToExistFolder.Text;
                        FClientData.FolderMode = "ExistFolder";
                    }
                    else if (rbAddToNewFolder.Checked)
                    {
                        FClientData.FolderName = tbAddToNewFolder.Text;
                        FClientData.FolderMode = "NewFolder";
                    }
                    if (rbCurrentSolution.Checked)
                    {
                        FClientData.SolutionName = tbCurrentSolution.Text;
                    }
                    if (rbAddToExistSolution.Checked)
                    {
                        FClientData.SolutionName = tbSolutionName.Text;
                    }
                    FClientData.WebSiteName = cbWebSite.Text;
                    GetTemplatePages();
                    DisplayPage(tpFormSetting);
                }
            }
            else if (tabControl.SelectedTab.Equals(tpFormSetting))
            {
                if (cbWebForm.Text == "")
                {
                    MessageBox.Show("Please select EEP Web Templates Form !!");
                    if (cbWebForm.CanFocus)
                    {
                        cbWebForm.Focus();
                    }
                }
                else if (tbFormName.Text == "")
                {
                    MessageBox.Show("Please input Form Name !!");
                    if (tbFormName.CanFocus)
                    {
                        tbFormName.Focus();
                    }
                }
                else
                {
                    if (FTemplatePage == null || FClientData.BaseFormName != cbWebForm.Text)
                    {
                        ClearFormData();
                        OpenTemplatePage();
#if VS90
                        InitDataComponentList(FDesignerDocument.webControls.GetEnumerator(), null);
#else
                        InitDataComponentList(FTemplatePage, null);
#endif
                        InitTemplateFormContainer();
                    }
                    FClientData.FormName = tbFormName.Text;
                    FClientData.FormTitle = tbFormTitle.Text;
                    if (cbWebForm.Text.EndsWith(".aspx"))
                        cbWebForm.Text = cbWebForm.Text.Remove(cbWebForm.Text.IndexOf(".aspx"));
                    FClientData.BaseFormName = cbWebForm.Text;
                    DisplayPage(tpProvider);
                }
            }
            else if (tabControl.SelectedTab.Equals(tpProvider))
            {
                DisplayPage(tpDataSource);
            }
            else if (tabControl.SelectedTab.Equals(tpDataSource))
            {
                DisplayPage(tpLayout);
            }
            BringToFront();
        }

        private void OpenTemplatePage()
        {
            FTemplatePage = null;
            IDesignerHost FDesignerHost = null;
            foreach (Project P in FDTE2.Solution.Projects)
            {
                if (string.Compare(P.Name, cbWebSite.Text) == 0)
                {
                    foreach (ProjectItem PI in P.ProjectItems)
                    {
                        if (string.Compare(PI.Kind, "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}") == 0)
                        {
                            if (PI.Name.CompareTo("Template") == 0)
                            {
                                foreach (ProjectItem PageItem in PI.ProjectItems)
                                {
                                    if (PageItem.Name.CompareTo(cbWebForm.Text) == 0)
                                    {
#if VS90 
                                        FDesignWindow = PageItem.Open("{7651A702-06E5-11D1-8EBD-00A0C90F26EA}");
                                        FDesignWindow.Activate();

                                        //EnvDTE90.HTMLWindow3 W = (EnvDTE90.HTMLWindow3)FDesignWindow.Object;
                                        //W.CurrentPane = EnvDTE90.vsHTMLPanes.vsHTMLPaneDesign;
                                        //W.CurrentView = EnvDTE90.vsHTMLViews.vsHTMLViewDesign;

                                        HTMLWindow W = (HTMLWindow)FDesignWindow.Object;
                                        //W.CurrentTab = vsHTMLTabs.vsHTMLTabsSource;
                                        //TextWindow FTextWindow;
                                        //if (W.CurrentTabObject is TextWindow)
                                        //    FTextWindow = W.CurrentTabObject as TextWindow;
                                        W.CurrentTab = vsHTMLTabs.vsHTMLTabsDesign;
                                        if (W.CurrentTabObject is WebDevPage.DesignerDocument)
                                        {
                                            FDesignerDocument = W.CurrentTabObject as WebDevPage.DesignerDocument;
                                        }
#else

                                        FDesignWindow = PageItem.Open("{00000000-0000-0000-0000-000000000000}");
                                        FDesignWindow.Activate();
                                        FDesignWindow = PageItem.Open("{7651A702-06E5-11D1-8EBD-00A0C90F26EA}");
                                        FDesignWindow.Activate();

                                        //FHtmlDocument = (HtmlDocument)aW.Document;
                                        HTMLWindow W = (HTMLWindow)FDesignWindow.Object;
                                        object o = W.CurrentTabObject;

                                        IntPtr pObject;
                                        Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSP = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)o;
                                        Guid sid = typeof(IVSMDDesigner).GUID;
                                        Guid iid = typeof(IVSMDDesigner).GUID;
                                        int hr = oleSP.QueryService(ref sid, ref iid, out pObject);
                                        System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr);
                                        if (pObject != IntPtr.Zero)
                                        {
                                            try
                                            {
                                                Object TempObj = Marshal.GetObjectForIUnknown(pObject);
                                                if (TempObj is IDesignerHost)
                                                {
                                                    FDesignerHost = (IDesignerHost)TempObj;
                                                }
                                                else
                                                {
                                                    Object ObjContainer = TempObj.GetType().InvokeMember("ComponentContainer",
                                                        System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public |
                                                        System.Reflection.BindingFlags.GetProperty, null, TempObj, null);
                                                    if (ObjContainer is IDesignerHost)
                                                    {
                                                        FDesignerHost = (IDesignerHost)ObjContainer;
                                                    }
                                                }
                                                FTemplatePage = (System.Web.UI.Page)FDesignerHost.RootComponent;
                                                Application.DoEvents();
                                            }
                                            finally
                                            {
                                                Marshal.Release(pObject);
                                            }
                                        }
#endif
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private void InitDataComponentList(Page WebPage, System.Web.UI.WebControls.WebControl ParentControl)
        {
            if (WebPage != null)
            {
                foreach (System.Web.UI.Control WC in WebPage.Controls)
                {
                    if (WC is WebDataSource)
                    {
                        DisplayPage(tpProvider);
                        System.Windows.Forms.ListViewItem ViewItem = null;
                        System.Windows.Forms.ListViewItem.ListViewSubItem SubItem = null;
                        InfoDataSet aDataSet = FClientData.FindDataSet(((WebDataSource)WC).WebDataSetID);
                        if (aDataSet == null)
                        {
                            ViewItem = lvWebDataSet.Items.Add(((WebDataSource)WC).WebDataSetID);
                            ViewItem.SubItems.Add("");
                            SubItem = ViewItem.SubItems.Add("");
                            CreateRefValButton(lvWebDataSet, ViewItem, SubItem, btnSelectProvider_Click);
                            aDataSet = new InfoDataSet(FContainer);
                            aDataSet.SetWizardDesignMode(true);
                            aDataSet.Site.Name = ViewItem.Text;
                            FClientData.DataSetList.Add(aDataSet);
                        }

                        DisplayPage(tpDataSource);
                        ViewItem = lvWebDataSource.Items.Add(((WebDataSource)WC).ID);
                        ViewItem.SubItems.Add("");
                        SubItem = ViewItem.SubItems.Add("");
                        cbWebDataSource.Items.Add(ViewItem.Text);
                        CreateRefValButton(lvWebDataSource, ViewItem, SubItem, btnSelectDataMember_Click);
                        InfoBindingSource DataSource = FClientData.FindDataSource(ViewItem.Text);
                        if (DataSource == null)
                        {
                            DataSource = new InfoBindingSource(FContainer);
                            DataSource.Site.Name = ViewItem.Text;
                            DataSource.text = aDataSet.Site.Name;
                            FClientData.DataSourceList.Add(DataSource);
                        }
                    }
                }
            }
        }

        private void InitDataComponentList(IEnumerator iEnum, System.Web.UI.WebControls.WebControl ParentControl)
        {
            while (iEnum.MoveNext())
            {
                if (iEnum.Current != null)
                {
                    IHTMLElement iHtmlE = iEnum.Current as IHTMLElement;
                    String tag = iHtmlE.tagName.Substring(iHtmlE.tagName.IndexOf(':') + 1);
                    if (tag == "webdatasource")
                    {
                        DisplayPage(tpProvider);
                        System.Windows.Forms.ListViewItem ViewItem = null;
                        System.Windows.Forms.ListViewItem.ListViewSubItem SubItem = null;

                        InfoDataSet aDataSet = FClientData.FindDataSet(iHtmlE.getAttribute("WebDataSetID", 0).ToString());
                        if (aDataSet == null)
                        {
                            ViewItem = lvWebDataSet.Items.Add(iHtmlE.getAttribute("WebDataSetID", 0).ToString());
                            ViewItem.SubItems.Add("");
                            SubItem = ViewItem.SubItems.Add("");
                            CreateRefValButton(lvWebDataSet, ViewItem, SubItem, btnSelectProvider_Click);
                            aDataSet = new InfoDataSet(FContainer);
                            aDataSet.SetWizardDesignMode(true);
                            aDataSet.Site.Name = ViewItem.Text;
                            FClientData.DataSetList.Add(aDataSet);
                        }

                        DisplayPage(tpDataSource);
                        ViewItem = lvWebDataSource.Items.Add(iHtmlE.id);
                        ViewItem.SubItems.Add("");
                        SubItem = ViewItem.SubItems.Add("");
                        cbWebDataSource.Items.Add(ViewItem.Text);
                        CreateRefValButton(lvWebDataSource, ViewItem, SubItem, btnSelectDataMember_Click);
                        InfoBindingSource DataSource = FClientData.FindDataSource(ViewItem.Text);
                        if (DataSource == null)
                        {
                            DataSource = new InfoBindingSource(FContainer);
                            DataSource.Site.Name = ViewItem.Text;
                            DataSource.text = aDataSet.Site.Name;
                            FClientData.DataSourceList.Add(DataSource);
                        }
                    }
                }

            }
        }

        private void CreateRefValButton(System.Windows.Forms.ListView View, System.Windows.Forms.ListViewItem Item, System.Windows.Forms.ListViewItem.ListViewSubItem SubItem, EventHandler ClickEvent)
        {
            System.Windows.Forms.Button B = new System.Windows.Forms.Button();
            B.Parent = View;
            RearrangeRefValButton(B, SubItem.Bounds);
            B.BackColor = Color.Silver;
            B.BringToFront();
            SubItem.Tag = B;
            B.Tag = Item;
            B.Click += new EventHandler(ClickEvent);
            B.Text = "...";
        }

        private void InitTemplateFormContainer()
        {
            System.Windows.Forms.TreeNode FormNode = tvContainer.Nodes.Add(tbFormName.Text);
#if VS90
            TNodeObject NodeObject = new TNodeObject(FormNode, FClientData, FDesignerDocument);
            NodeObject.BlockItem.ContainerName = tbFormName.Text;
            BuildContainerTree(FDesignerDocument.webControls.GetEnumerator(), FormNode);
#else
            TNodeObject NodeObject = new TNodeObject(FormNode, FClientData, FTemplatePage);
            NodeObject.BlockItem.ContainerName = tbFormName.Text;
            BuildContainerTree(FTemplatePage.Controls, FormNode);
#endif
            tvContainer.ExpandAll();
        }

        private void CreateTreeNode(System.Windows.Forms.TreeNode ParentNode, Object ChildControl)
        {
            System.Windows.Forms.TreeNode ChildNode = new System.Windows.Forms.TreeNode();
            PropertyInfo aInfo = ChildControl.GetType().GetProperty("ID");
            if (aInfo != null)
            {
                ChildNode.Text = aInfo.GetValue(ChildControl, null) as String;
            }
            ParentNode.Nodes.Add(ChildNode);
            TNodeObject NodeObject = new TNodeObject(ChildNode, FClientData, (WebControl)ChildControl);
            aInfo = ChildControl.GetType().GetProperty("DataSourceID");
            if (aInfo != null)
            {
                String DataSourceID = aInfo.GetValue(ChildControl, null) as String;
                InfoBindingSource DataSource = FClientData.FindDataSource(DataSourceID);
                NodeObject.BlockItem.BindingSource = DataSource;
            }
        }

        private void BuildContainerTree(System.Web.UI.ControlCollection ParentControl, System.Windows.Forms.TreeNode ParentNode)
        {
            foreach (Object ChildControl in ParentControl)
            {
                if (ChildControl is WebGridView || ChildControl is WebFormView || ChildControl is GridView 
                    || ChildControl is WebDetailsView || ChildControl is UpdatePanel || ChildControl is MultiView
                    || ChildControl is System.Web.UI.WebControls.View)
                {
                    System.Windows.Forms.TreeNode ChildNode = new System.Windows.Forms.TreeNode();
                    PropertyInfo aInfo = ChildControl.GetType().GetProperty("ID");
                    if (aInfo != null)
                    {
                        ChildNode.Text = aInfo.GetValue(ChildControl, null) as String;
                    }
                    ParentNode.Nodes.Add(ChildNode);
                    TNodeObject NodeObject = new TNodeObject(ChildNode, FClientData, ChildControl);
                    aInfo = ChildControl.GetType().GetProperty("DataSourceID");
                    if (aInfo != null)
                    {
                        String DataSourceID = aInfo.GetValue(ChildControl, null) as String;
                        InfoBindingSource DataSource = FClientData.FindDataSource(DataSourceID);
                        NodeObject.BlockItem.BindingSource = DataSource;
                    }

                    aInfo = ChildControl.GetType().GetProperty("Controls");
                    if (aInfo != null)
                    {
                        BuildContainerTree(aInfo.GetValue(ChildControl, null) as System.Web.UI.ControlCollection, ChildNode);
                    }

                }
            }

            return;
            //if (WebPage != null)
            //{
            //    foreach (Object ChildControl in WebPage.Controls)
            //    {
            //        CreateTreeNode(ParentNode, ChildControl);
            //    }
            //}
            //else
            //{
            //    foreach (Object ChildControl in ParentControl.Controls)
            //    {
            //        CreateTreeNode(ParentNode, ChildControl);
            //    }
            //}
        }

        private void BuildContainerTree(IEnumerator iEnum, System.Windows.Forms.TreeNode ParentNode)
        {
            while (iEnum.MoveNext())
            {
                if (iEnum.Current != null)
                {
                    IHTMLElement iHtmlE = iEnum.Current as IHTMLElement;
                    String tag = iHtmlE.tagName.Substring(iHtmlE.tagName.IndexOf(':') + 1);
                    if (tag == "webgridview" || tag == "webformview" || tag == "gridview" || tag == "webdetailsview")
                        //|| tag == "updatepanel" || tag == "multiview" || tag == "view")
                    {
                        System.Windows.Forms.TreeNode ChildNode = new System.Windows.Forms.TreeNode();
                        ChildNode.Text = iHtmlE.id;
                        ParentNode.Nodes.Add(ChildNode);
                        object Container = null;
                        switch (tag)
                        {
                            case "webgridview":
                                Container = new WebGridView();
                                (Container as WebGridView).ID = iHtmlE.id;
                                (Container as WebGridView).DataSourceID = iHtmlE.getAttribute("DataSourceID", 0).ToString();
                                break;
                            case "webformview":
                                Container = new WebFormView();
                                (Container as WebFormView).ID = iHtmlE.id;
                                (Container as WebFormView).DataSourceID = iHtmlE.getAttribute("DataSourceID", 0).ToString();
                                break;
                            case "webdetailsview":
                                Container = new WebDetailsView();
                                (Container as WebDetailsView).ID = iHtmlE.id;
                                (Container as WebDetailsView).DataSourceID = iHtmlE.getAttribute("DataSourceID", 0).ToString();
                                break;
                            case "gridview":
                                Container = new GridView();
                                (Container as GridView).ID = iHtmlE.id;
                                (Container as GridView).DataSourceID = iHtmlE.getAttribute("DataSourceID", 0).ToString();
                                break;
                            case "updatepanel":
                                Container = new UpdatePanel();
                                break;
                            case "multiview":
                                Container = new MultiView();
                                break;
                            case "view":
                                Container = new System.Web.UI.WebControls.View();
                                break;

                        }
                        TNodeObject NodeObject = new TNodeObject(ChildNode, FClientData, Container);
                        String dataSourceID = iHtmlE.getAttribute("DataSourceID", 0).ToString();
                        if (dataSourceID != null && dataSourceID != String.Empty)
                        {
                            InfoBindingSource DataSource = FClientData.FindDataSource(dataSourceID);
                            NodeObject.BlockItem.BindingSource = DataSource;
                        }

                        //aInfo = ChildControl.GetType().GetProperty("Controls");
                        //if (aInfo != null)
                        //{
                        //    BuildContainerTree(aInfo.GetValue(ChildControl, null) as System.Web.UI.ControlCollection, ChildNode);
                        //}
                    }
                }
            }


            //foreach (Object ChildControl in ParentControl)
            //{
            //    if (ChildControl is WebGridView || ChildControl is WebFormView || ChildControl is GridView 
            //        || ChildControl is WebDetailsView || ChildControl is UpdatePanel || ChildControl is MultiView
            //        || ChildControl is System.Web.UI.WebControls.View)
            //    {
            //        System.Windows.Forms.TreeNode ChildNode = new System.Windows.Forms.TreeNode();
            //        PropertyInfo aInfo = ChildControl.GetType().GetProperty("ID");
            //        if (aInfo != null)
            //        {
            //            ChildNode.Text = aInfo.GetValue(ChildControl, null) as String;
            //        }
            //        ParentNode.Nodes.Add(ChildNode);
            //        TNodeObject NodeObject = new TNodeObject(ChildNode, FClientData, ChildControl);
            //        aInfo = ChildControl.GetType().GetProperty("DataSourceID");
            //        if (aInfo != null)
            //        {
            //            String DataSourceID = aInfo.GetValue(ChildControl, null) as String;
            //            InfoBindingSource DataSource = FClientData.FindDataSource(DataSourceID);
            //            NodeObject.BlockItem.BindingSource = DataSource;
            //        }

            //        aInfo = ChildControl.GetType().GetProperty("Controls");
            //        if (aInfo != null)
            //        {
            //            BuildContainerTree(aInfo.GetValue(ChildControl, null) as System.Web.UI.ControlCollection, ChildNode);
            //        }

            //    }
            //}

            return;
            //if (WebPage != null)
            //{
            //    foreach (Object ChildControl in WebPage.Controls)
            //    {
            //        CreateTreeNode(ParentNode, ChildControl);
            //    }
            //}
            //else
            //{
            //    foreach (Object ChildControl in ParentControl.Controls)
            //    {
            //        CreateTreeNode(ParentNode, ChildControl);
            //    }
            //}
        }

        private void GetTemplatePages()
        {
            cbWebForm.Items.Clear();

            List<String> AspxsFiles = new List<string>();
            List<String> CodeFiles = new List<string>();
            foreach (Project P in FDTE2.Solution.Projects)
            {
                if (string.Compare(P.Name, cbWebSite.Text) == 0)
                {
                    foreach (ProjectItem PI in P.ProjectItems)
                    {
                        if (string.Compare(PI.Kind, "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}") == 0)
                        {
                            if (PI.Name.CompareTo("Template") == 0)
                            {
                                foreach (ProjectItem aPage in PI.ProjectItems)
                                {
                                    if (Path.GetExtension(aPage.Name).CompareTo(".aspx") == 0)
                                        AspxsFiles.Add(aPage.Name);
                                    if (Path.GetExtension(aPage.Name).CompareTo("." + FClientData.Language) == 0)
                                        CodeFiles.Add(aPage.Name);
                                }
                            }
                        }
                    }
                }
            }

            foreach (String FileName in CodeFiles)
            {
                String S = Path.GetFileNameWithoutExtension(FileName);
                if (AspxsFiles.IndexOf(S) > -1)
                    cbWebForm.Items.Add(S);
            }
            //foreach (Project P in FDTE2.Solution.Projects)
            //{
            //    if (FClientData.TemplatePath == null || FClientData.TemplatePath == "")
            //        FClientData.TemplatePath = Path.GetDirectoryName(FDTE2.Solution.FullName) + "\\Template\\";

            //    if (P.Name.CompareTo("Template") == 0 && P.Kind == "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}")
            //    {
            //        foreach (ProjectItem PI in P.ProjectItems)
            //        {
            //            if (PI.SubProject.CodeModel.Language.ToString().CompareTo(Language) == 0)
            //            {
            //                cbBaseForm.Items.Add(PI.Name);
            //            }
            //        }
            //    }
            //}
            if (cbWebForm.Items.Count > 0)
                this.cbWebForm.SelectedIndex = 0;
        }

        private void btnPrevious_Click(object sender, EventArgs e)
		{
            if (tabControl.SelectedTab.Equals(tpOutputSetting))
            {
                DisplayPage(tpConnection);
            }
            else if (tabControl.SelectedTab.Equals(tpFormSetting))
            {
                DisplayPage(tpOutputSetting);
            }
            else if (tabControl.SelectedTab.Equals(tpProvider))
            {
                DisplayPage(tpFormSetting);
            }
            else if (tabControl.SelectedTab.Equals(tpDataSource))
            {
                DisplayPage(tpProvider);
            }
            else if (tabControl.SelectedTab.Equals(tpLayout))
            {
                DisplayPage(tpDataSource);
            }
		}

        private String GetRelationName(InfoDataSet aDataSet, DataRelationCollection Relations, String DataSetName)
        {
            String Result = "";
            if (aDataSet != null)
            {
                for (int i = 0; i < aDataSet.RealDataSet.Tables.Count; i++)
                {
                    if (aDataSet.RealDataSet.Tables[i].TableName.CompareTo(DataSetName) == 0)
                        Result = DataSetName;
                }
                if (Result == "")
                    Result = GetRelationName(null, aDataSet.RealDataSet.Relations, DataSetName);
            }
            else
            {
                foreach (DataRelation Relation in Relations)
                {
                    if (Relation.ChildTable.TableName.CompareTo(DataSetName) == 0)
                        return Relation.RelationName;
                    Result = GetRelationName(null, Relation.ChildTable.ChildRelations, DataSetName);
                    if (Result != "")
                        return Result;
                }
            }
            return Result;
        }

        private void btnSelectDataMember_Click(object sender, EventArgs e)
        {
            fmSelectProvider aForm = new fmSelectProvider();
            String ProviderName = "";
            if (aForm.ShowSelectProviderForm(FClientData.DataSetList, ref ProviderName))
            {
                System.Windows.Forms.ListViewItem ViewItem = (System.Windows.Forms.ListViewItem)((System.Windows.Forms.Button)sender).Tag;
                InfoBindingSource DataSource = FClientData.FindDataSource(ViewItem.Text);
                InfoDataSet aDataSet = FClientData.FindDataSet(DataSource.text);

                String DataSetName = ProviderName;
                String ModuleName = aDataSet.RemoteName.Substring(0, aDataSet.RemoteName.IndexOf('.'));
                String SolutionName = System.IO.Path.GetFileNameWithoutExtension(FDTE2.Solution.FullName);
                String TableName = CliUtils.GetTableName(ModuleName, DataSetName, SolutionName);
                TableName = WzdUtils.GetToken(ref TableName, new char[] { '.' });
                if (TableName.Contains("[") && TableName.Contains("]"))
                {
                    String[] temp = TableName.Split(new char[] { '[', ']' });
                    TableName = temp[1];
                }

                try
                {
                    DataSource.DataMember = GetRelationName(aDataSet, null, ProviderName);
                    DataSource.Tablename = TableName;
                    
                    List<TBlockItem> aList = FClientData.FindBlockItemByDataSource(DataSource);
                    foreach (TBlockItem BlockItem in aList)
                    {
                        BlockItem.TableName = TableName;
                        BlockItem.ProviderName = ProviderName;
                    }
                }
                catch
                {
                    MessageBox.Show("While Setting DataMember occurs error, please check master BindingSource had been setup correctly. ");
                    return;
                }
                ViewItem.SubItems[1].Text = ProviderName;
            }
        }

		private void btnCancel_Click(object sender, EventArgs e)
		{
            Hide();
		}

        private void SelectFields(System.Windows.Forms.ListView lvSrc, System.Windows.Forms.ListView lvDes, Boolean All)
	    {
            int I;
            System.Windows.Forms.ListViewItem Item;
            System.Windows.Forms.ListViewItem.ListViewSubItem LVSI;

            for (I = 0; I < lvSrc.Items.Count; I++)
            {
                if (lvSrc.Items[I].Selected || All)
                {
                    Item = new System.Windows.Forms.ListViewItem(lvSrc.Items[I].Text);
                    Item.Tag = lvSrc.Items[I].Tag;
                    if (lvSrc.Items[I].SubItems.Count > 1)
                        Item.SubItems.Add(lvSrc.Items[I].SubItems[1]);
                    else
                        Item.SubItems.Add("");
                    lvDes.Items.Add(Item);
                    if (lvDes.Columns.Count == 3)
                    {
                        LVSI = Item.SubItems.Add("");
                        System.Windows.Forms.Button B = new System.Windows.Forms.Button();
                        B.Parent = lvDes;
                        RearrangeRefValButton(B, LVSI.Bounds);
                        B.BackColor = Color.Silver;
                        B.BringToFront();
                        LVSI.Tag = B;
                        B.Tag = Item;
                        B.Click += new EventHandler(btnRefVal_Click);
                        B.Text = "...";
                    }
                }
            }

            for (I = lvSrc.Items.Count - 1; I >= 0; I--)
            {
                if (lvSrc.Items[I].Selected || All)
                {
                    if (lvSrc.Columns.Count == 3)
                    {
                        LVSI = lvSrc.Items[I].SubItems[2];
                        if (LVSI != null)
                        {
                            if (LVSI.Tag != null)
                            {
                                ((System.Windows.Forms.Button)LVSI.Tag).Dispose();
                            }
                        }
                    }
                    lvSrc.Items[I].Remove();
                }
            }

            if (lvSrc.Columns.Count == 3)
            {
                foreach (System.Windows.Forms.ListViewItem LVI in lvSrc.Items)
                {
                    LVSI = LVI.SubItems[2];
                    if (LVSI.Tag != null)
                        RearrangeRefValButton((System.Windows.Forms.Button)LVSI.Tag, LVSI.Bounds);
                }
            }
        }

        public delegate void RearrangeRefValButtonFunc(System.Windows.Forms.Button B, Rectangle Bounds);

        private void RearrangeRefValButton(System.Windows.Forms.Button B, Rectangle Bounds)
        {
            Rectangle NewBounds = new Rectangle();
            if (Bounds.Width > 20000)
            {
                NewBounds.X = Bounds.X + Bounds.Width - 20;
                NewBounds.Width = 20;
            }
            else
            {
                NewBounds.X = Bounds.X;
                NewBounds.Width = Bounds.Width;
            }
            NewBounds.Y = Bounds.Y - 1;
            NewBounds.Height = Bounds.Height - 2;
            B.Bounds = NewBounds;
        }

        private void DoGenClient()
        {
            FClientData.FormName = tbFormName.Text;
            TExtWebClientGenerator Generator = new TExtWebClientGenerator(FClientData, FDTE2, FAddIn);
            Generator.GenWebClientModule();
        }

        private void btnDone_Click(object sender, EventArgs e)
		{
            Hide();
            FDTE2.MainWindow.Activate();
            DoGenClient();
        }

		private void button2_Click(object sender, EventArgs e)
		{
            FClientData.FormName = tbFormName.Text;
            TExtWebClientGenerator G = new TExtWebClientGenerator(FClientData, FDTE2, FAddIn);
            G.GenWebClientModule();
            Close();
		}

        private void GetWebSite()
        {
            cbWebSite.Items.Clear();
            foreach (Project P in FDTE2.Solution.Projects)
            {
                if (string.Compare(P.Kind, "{E24C65DC-7377-472b-9ABA-BC803B73C61A}") == 0)
                {
                    cbWebSite.Items.Add(P.Name);
                }
            }

            if (cbWebSite.Items.Count == 1)
            {
                cbWebSite.SelectedIndex = 0;
                cbWebSite_SelectedIndexChanged(cbWebSite, new EventArgs());
            }
        }

        private void btnSolutionName_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbSolutionName.Text = openFileDialog.FileName;
                if (string.Compare(tbSolutionName.Text, FDTE2.Solution.FullName) != 0)
                {
                    FDTE2.Solution.Open(tbSolutionName.Text);
                }
                GetWebSite();
            }
        }

        private void EnabledOutputControls()
        {
        }

        private void rbNewSolution_Click(object sender, EventArgs e)
        {
            EnabledOutputControls();
        }

        private void rbAddToExistSln_Click(object sender, EventArgs e)
        {
            EnabledOutputControls();
        }

        private void rbAddToCurrent_Click(object sender, EventArgs e)
        {
            EnabledOutputControls();
        }

        private void btnConnectionString_Click(object sender, EventArgs e)
        {
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string s = "C:\\Program Files\\Infolight\\EEP2006\\EEPNetServer\\WindowsApplication1\\SSingle.dll";
            string sDll = "SSingle";
            FileStream fs = null;
            fs = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] b = new byte[fs.Length];
            fs.Read(b, 0, (int)fs.Length);

            // Add By Chenjian, Can not delete dll file if FileStream is not closed
            fs.Close();
            // End Add

            Assembly a = Assembly.Load(b);
            try
            {
                Type myType = a.GetType(sDll + ".Component", true,  true);
                if (myType != null)
                    MessageBox.Show("get");
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message);
            }
        }

        public delegate void GetFieldNamesFunc(string DatabaseName, string TableName, String DataSetName, System.Windows.Forms.ListView SrcListView, System.Windows.Forms.ListView DestListView);

        public void GetFieldNames(string DatabaseName, string TableName, String DataSetName, System.Windows.Forms.ListView SrcListView, System.Windows.Forms.ListView DestListView)
        {
            System.Windows.Forms.TreeNode Node = tvContainer.SelectedNode;
            if (Node == null)
                return;
            InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
            aInfoCommand.Connection = InternalConnection;
            TableName = WzdUtils.RemoveQuote(TableName, FClientData.DatabaseType);
            aInfoCommand.CommandText = "Select * from COLDEF where TABLE_NAME = '" + TableName + "'";
            IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
            DataSet dsColdef = new DataSet();
            WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, dsColdef, "COLDEF");

            InfoBindingSource DataSource = ((TNodeObject)Node.Tag).BlockItem.BindingSource;
            InfoDataSet aDataSet = FClientData.FindDataSet(DataSource.text);
            int Index = aDataSet.RealDataSet.Tables.IndexOf(WzdUtils.RemoveSpace(DataSetName));
            DataTable Table = aDataSet.RealDataSet.Tables[Index];

            int I;
            System.Windows.Forms.ListViewItem ViewItem;
            for (I = 0; I < DestListView.Items.Count; I++)
            {
                ViewItem = DestListView.Items[I];
                if (Table.Columns.IndexOf(ViewItem.Text) < 0)
                { 
                    if (ViewItem.Tag != null)
                        if (ViewItem.Tag.GetType().Equals(typeof(TBlockFieldItem)))
                        {
                            TBlockFieldItem B = (TBlockFieldItem)ViewItem.Tag;
                            B.Collection.Remove(B);
                        }
                }
            }

            SrcListView.Items.Clear();
            bool Found;
            int J;
            DataRow[] DRs = null;
            for (I = 0; I < Table.Columns.Count; I++)
            {
                Found = false;
                for (J = 0; J < DestListView.Items.Count; J++)
                {
                    ViewItem = DestListView.Items[J];
                    if (string.Compare(Table.Columns[I].ColumnName, ViewItem.Text, false) == 0)
                    {
                        Found = true;
                        break;
                    }
                }
                if (Found == false)
                {
                    TBlockFieldItem FieldItem = new TBlockFieldItem();
                    FieldItem.DataField = Table.Columns[I].ColumnName;
                    FieldItem.DataType = Table.Columns[I].DataType;
                    ViewItem = SrcListView.Items.Add(Table.Columns[I].ColumnName);
                    ViewItem.Tag = FieldItem;
                    DRs = dsColdef.Tables[0].Select("TABLE_NAME = '" + TableName + "' and FIELD_NAME = '" + Table.Columns[I].ColumnName + "'");
                    if (DRs.Length == 1)
                    {
                        FieldItem.Description = DRs[0]["CAPTION"].ToString();
                        FieldItem.CheckNull = DRs[0]["CHECK_NULL"].ToString();
                        FieldItem.DefaultValue = DRs[0]["DEFAULT_VALUE"].ToString();
                        FieldItem.IsKey = DRs[0]["IS_KEY"].ToString().ToUpper() == "Y";
                        FieldItem.ControlType = DRs[0]["NEEDBOX"].ToString();
                        FieldItem.EditMask = DRs[0]["EDITMASK"].ToString();
                        FieldItem.QueryMode = DRs[0]["QUERYMODE"].ToString();
                        if (DRs[0]["FIELD_LENGTH"] != null)
                            FieldItem.Length = int.Parse(DRs[0]["FIELD_LENGTH"].ToString());
                        if (FieldItem.DataType == typeof(DateTime))
                        {
                            if (FieldItem.ControlType == null || FieldItem.ControlType == "")
                                FieldItem.ControlType = "DateTimeBox";
                        }
                    }
                    ViewItem.SubItems.Add(FieldItem.Description);
                }
            }
        }

        public String FindDBType(String aliasName)
        {
            String xmlName = SystemFile.DBFile;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlName);

            XmlNode node = xmlDoc.FirstChild.FirstChild.SelectSingleNode(aliasName);

            string DbType = node.Attributes["Type"].Value.Trim();
            return DbType;
        }

        private void cbEEPAlias_SelectedIndexChanged(object sender, EventArgs e)
        {
            string type = FindDBType(cbEEPAlias.Text);
            int num1 = FAlias.IndexOf(cbEEPAlias.Text);
            tbConnectionString.Text = (string)FAlias.Objects(num1);
            FClientData.DatabaseName = this.cbEEPAlias.Text;
            switch (type)
            {
                case "1":
                    FClientData.DatabaseType = ClientType.ctMsSql; break;
                case "2":
                    FClientData.DatabaseType = ClientType.ctOleDB; break;
                case "3":
                    FClientData.DatabaseType = ClientType.ctOracle; break;
                case "4":
                    FClientData.DatabaseType = ClientType.ctODBC; break;
                case "5":
                    FClientData.DatabaseType = ClientType.ctMySql; break;
                case "6":
                    FClientData.DatabaseType = ClientType.ctInformix; break;
            }
            cbDatabaseType.SelectedIndex = (int)FClientData.DatabaseType;
            if (InternalConnection == null)
            {
                InternalConnection = WzdUtils.AllocateConnection(this.cbEEPAlias.Text, FClientData.DatabaseType, false);
                this.FClientData.ConnString = InternalConnection.ConnectionString;
            }
            else
            {
                if (InternalConnection.State == ConnectionState.Open)
                    InternalConnection.Close();
                InternalConnection = WzdUtils.AllocateConnection(this.cbEEPAlias.Text, FClientData.DatabaseType, false);
                //InternalConnection.ConnectionString = tbConnectionString.Text;
            }

            if (InternalConnection.ConnectionString.Trim() != "")
            {
                try
                {
                    InternalConnection.Open();
                }
                catch (Exception E)
                {
                    MessageBox.Show(string.Format("Database ConnnectionString information error, please reset ConnectionString.\nThe error message:\n{0}", E.Message));
                }
            }
        }

        private void EnableFolderControl()
        {
            cbAddToExistFolder.Enabled = rbAddToExistFolder.Checked;
            tbAddToNewFolder.Enabled = rbAddToNewFolder.Checked;
        }

        private void rbAddToRootFolder_CheckedChanged(object sender, EventArgs e)
        {
            EnableFolderControl();
        }

        private void rbAddToExistFolder_CheckedChanged(object sender, EventArgs e)
        {
            EnableFolderControl();
        }

        private void rbAddToNewFolder_CheckedChanged(object sender, EventArgs e)
        {
            EnableFolderControl();
        }

        private void cbWebSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbAddToExistFolder.Items.Clear();
            foreach (Project P in FDTE2.Solution.Projects)
            {
                if (string.Compare(P.Name, cbWebSite.Text) == 0)
                {
                    foreach (ProjectItem PI in P.ProjectItems)
                    {
                        if (string.Compare(PI.Kind, "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}") == 0)
                        {
                            cbAddToExistFolder.Items.Add(PI.Name);
                        }
                    }
                }
            }
            if (cbAddToExistFolder.Items.Count > 0)
            {
                rbAddToExistFolder.Checked = true;
                rbAddToExistFolder_CheckedChanged(rbAddToExistFolder, null);
            }
            else
            {
                rbAddToNewFolder.Checked = true;
                rbAddToNewFolder_CheckedChanged(rbAddToNewFolder, null);
            }
        }

        private void SolutionCheckedChange()
        {
            if (rbCurrentSolution.Checked)
            {
                tbSolutionName.Enabled = false;
                btnSolutionName.Enabled = false;
            }
            if (rbAddToExistSolution.Checked)
            {
                tbSolutionName.Enabled = true;
                btnSolutionName.Enabled = true;
            }
        }

        private void rbCurrentSolution_CheckedChanged(object sender, EventArgs e)
        {
            SolutionCheckedChange();
        }

        private void rbAddToExistSolution_CheckedChanged(object sender, EventArgs e)
        {
            SolutionCheckedChange();
        }

        private void ClearRefValButton(System.Windows.Forms.ListView LV)
        {
            foreach (System.Windows.Forms.ListViewItem LVI in LV.Items)
            {
                if (LVI.SubItems.Count > 1)
                {
                    System.Windows.Forms.ListViewItem.ListViewSubItem LVSI = LVI.SubItems[2];
                    if (LVSI != null)
                    {
                        if (LVSI.Tag != null)
                        {
                            ((System.Windows.Forms.Button)LVSI.Tag).Dispose();
                        }
                    }
                }
            }
        }

        private void DisplayValue(System.Windows.Forms.ListView aListView)
        {
            foreach (System.Windows.Forms.ListViewItem aViewItem in aListView.Items)
            {
                TBlockFieldItem BlockFieldItem = (TBlockFieldItem)aViewItem.Tag;
                aViewItem.SubItems[1].Text = BlockFieldItem.Description;
            }
        }

        private void btnRefVal_Click(object sender, EventArgs e)
        {
            Object aObject = ((System.Windows.Forms.Button)sender).Tag;
            System.Windows.Forms.ListViewItem.ListViewSubItem LVSI = null;
            System.Windows.Forms.ListViewItem aViewItem = null;
            TBlockFieldItem BlockFieldItem = null;
            if (aObject.GetType().Equals(typeof(System.Windows.Forms.ListViewItem.ListViewSubItem)))
            {
                MessageBox.Show("This is wrong way");
                throw new Exception("");
                //LVSI = (ListViewItem.ListViewSubItem)((System.Windows.Forms.Button)sender).Tag;
                //BlockFieldItem = (TBlockFieldItem)LVSI.Tag;
            }
            if (aObject.GetType().Equals(typeof(System.Windows.Forms.ListViewItem)))
            {
                aViewItem = (System.Windows.Forms.ListViewItem)((System.Windows.Forms.Button)sender).Tag;
                BlockFieldItem = (TBlockFieldItem)aViewItem.Tag;
                LVSI = ((System.Windows.Forms.ListViewItem)aObject).SubItems[2];
            }

            fmFieldSetting aForm = new fmFieldSetting(InternalConnection, FClientData.DatabaseType, aViewItem.ListView, TWizardType.wtWebPage, FClientData.DatabaseName);
            try
            {

                String[] Params = new String[] { BlockFieldItem.Description, BlockFieldItem.CheckNull,
                    BlockFieldItem.DefaultValue, BlockFieldItem.ControlType, BlockFieldItem.RefValNo,
                    BlockFieldItem.ComboTableName, BlockFieldItem.ComboTextField, BlockFieldItem.ComboValueField, BlockFieldItem.EditMask};
                if (aForm.ShowRefValForm(Params))
                {
                    //BlockFieldItem.Description = Params[0];
                    //BlockFieldItem.CheckNull = Params[1].ToUpper();
                    //BlockFieldItem.DefaultValue = Params[2];
                    //BlockFieldItem.ControlType = Params[3];
                    //BlockFieldItem.RefValNo = Params[4];
                    //BlockFieldItem.ComboTableName = Params[5];
                    //BlockFieldItem.ComboTextField = Params[6];
                    //BlockFieldItem.ComboValueField = Params[7];
                }
                //LVSI.Text = Params[4];
                //aViewItem.SubItems[1].Text = BlockFieldItem.Description;
                DisplayValue(aViewItem.ListView);
            }
            finally
            {
                aForm.Dispose();
            }
        }

        private void lvMasterDesField_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
        {
            System.Windows.Forms.ListView LV = (System.Windows.Forms.ListView)sender;
            foreach (System.Windows.Forms.ListViewItem LVI in LV.Items)
            {
                System.Windows.Forms.ListViewItem.ListViewSubItem LVSI = LVI.SubItems[2];
                if (LVSI.Tag != null)
                {
                    System.Windows.Forms.Button B = (System.Windows.Forms.Button)LVSI.Tag;
                    RearrangeRefValButton(B, LVSI.Bounds);
                }
            }
        }

        private void cbDatabaseType_SelectedIndexChanged(object sender, EventArgs e)
        {
            FClientData.DatabaseType = (ClientType)cbDatabaseType.SelectedIndex;
        }

        private void tbFormName_TextChanged(object sender, EventArgs e)
        {
            tbFormTitle.Text = tbFormName.Text;
        }

        private void btnProviderName_Click(object sender, EventArgs e)
        {
            WebDataSet aDataSet = new WebDataSet();
            IGetValues aItem = (IGetValues)aDataSet;
            FProviderNameList = aItem.GetValues("RemoteName");
            string strSelected = "";
            PERemoteName form = new PERemoteName(FProviderNameList, strSelected);
            if (form.ShowDialog() == DialogResult.OK)
            {
                aDataSet.RemoteName = form.RemoteName;
                aDataSet.SetWizardDesignMode(true);
                aDataSet.Active = true;
                FClientData.ProviderName = form.RemoteName;
            }
        }

        private void EnableBindingInformation(TBlockItem BlockItem)
        {
            cbWebDataSource.Enabled = false;
            ClearRefValButton(lvSelectedFields);
            lvSelectedFields.Items.Clear();
            btnAddField.Enabled = false;
            btnDeleteField.Enabled = false;
            if (BlockItem.WebContainerControl is WebGridView || BlockItem.WebContainerControl is DetailsView ||
                BlockItem.WebContainerControl is WebFormView || BlockItem.WebContainerControl is GridView)
            {
                cbWebDataSource.Enabled = true;
                btnAddField.Enabled = true;
                btnDeleteField.Enabled = true;
            }
        }

        private void DisplaySelection(TBlockItem BlockItem)
        {
            cbWebDataSource.SelectedIndexChanged -= cbWebDataSource_SelectedIndexChanged;
            cbWebDataSource.Text = "";
            EnableBindingInformation(BlockItem);
            if (BlockItem.BindingSource != null)
                cbWebDataSource.Text = BlockItem.BindingSource.Site.Name;

            //Columns
            foreach (TBlockFieldItem BlockFieldItem in BlockItem.BlockFieldItems)
            {
                System.Windows.Forms.ListViewItem ListItem = lvSelectedFields.Items.Add(BlockFieldItem.DataField);
                ListItem.SubItems.Add(BlockFieldItem.Description);
                System.Windows.Forms.ListViewItem.ListViewSubItem LVSI = ListItem.SubItems.Add("");
                CreateRefValButton(lvSelectedFields, ListItem, LVSI, btnRefVal_Click);
                ListItem.Tag = BlockFieldItem;
            }
            cbWebDataSource.SelectedIndexChanged += cbWebDataSource_SelectedIndexChanged;
        }

        private void tvContainer_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag == null)
                return;
            TNodeObject NodeObject = (TNodeObject)e.Node.Tag;
            DisplaySelection(NodeObject.BlockItem);
        }

        private void btnSelectProvider_Click(object sender, EventArgs e)
        {
            WebDataSet aDataSet = new WebDataSet();
            IGetValues aItem = (IGetValues)aDataSet;
            String[] FProviderNameList = aItem.GetValues("RemoteName");
            String strSelected = "";
            PERemoteName form = new PERemoteName(FProviderNameList, strSelected);
            if (form.ShowDialog() == DialogResult.OK)
            {
                System.Windows.Forms.ListViewItem ViewItem = (System.Windows.Forms.ListViewItem)((System.Windows.Forms.Button)sender).Tag;
                ViewItem.SubItems[1].Text = form.RemoteName;
                InfoDataSet bDataSet = FClientData.FindDataSet(ViewItem.Text);
                bDataSet.RealDataSet.Tables.Clear();
                bDataSet.RemoteName = form.RemoteName;
                bDataSet.SetWizardDesignMode(true);
                bDataSet.Active = true;
            }
        }

        private void btnAddField_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.TreeNode Node = tvContainer.SelectedNode;
            if (Node != null)
            {
                TNodeObject NodeObject = (TNodeObject)Node.Tag;
                fmSelTableField F = new fmSelTableField();
                if (F.ShowSelTableFieldForm(NodeObject.BlockItem, GetFieldNames, lvSelectedFields, InternalConnection, RearrangeRefValButton, btnRefVal_Click, FClientData.DatabaseType))
                {
                    btnDeleteField.Enabled = lvSelectedFields.Items.Count > 0;
                }
            }
        }

        private void btnDeleteField_Click(object sender, EventArgs e)
        {
            if (tvContainer.SelectedNode == null)
                return;
            TNodeObject NodeObject = (TNodeObject)tvContainer.SelectedNode.Tag;
            TBlockItem BlockItem = NodeObject.BlockItem;
            foreach (System.Windows.Forms.ListViewItem aViewItem in lvSelectedFields.SelectedItems)
            {
                TBlockFieldItem FieldItem = BlockItem.BlockFieldItems.FindItem(aViewItem.Text);
                BlockItem.BlockFieldItems.Remove(FieldItem);
                if (aViewItem.SubItems.Count > 1 && aViewItem.SubItems[2].Tag != null)
                    ((System.Windows.Forms.Button)aViewItem.SubItems[2].Tag).Dispose();
                lvSelectedFields.Items.Remove(aViewItem);
            }
        }

        private String GetTableNameByBindingSource(InfoBindingSource aBindingSource)
        {
            if (aBindingSource.DataSource is InfoDataSet)
                return aBindingSource.DataMember;
            if (aBindingSource.DataSource is InfoBindingSource)
            {
                return aBindingSource.Tablename;
            }
            return "";
        }

        private void cbWebDataSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tvContainer.SelectedNode == null || tvContainer.SelectedNode.Tag == null)
                return;
            TNodeObject NodeObject = (TNodeObject)tvContainer.SelectedNode.Tag;
            NodeObject.BlockItem.BindingSource = FClientData.FindDataSource(cbWebDataSource.Text);
            if (NodeObject.BlockItem.BindingSource != null)
            {
                NodeObject.BlockItem.TableName = NodeObject.BlockItem.BindingSource.Tablename;
                NodeObject.BlockItem.ProviderName = NodeObject.BlockItem.TableName;
            }
        }

        private void fmExtEEPWebWizard_VisibleChanged(object sender, EventArgs e)
        {
            if (FDesignWindow != null)
                FDesignWindow.Close(vsSaveChanges.vsSaveChangesNo);
        }

        private void lvSelectedFields_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            ListViewColumnSorter lvwColumnSorter = (sender as System.Windows.Forms.ListView).ListViewItemSorter as ListViewColumnSorter;

            // 检查点击的列是不是现在的排序列.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // 重新设置此列的排序方法.
                if (lvwColumnSorter.OrderOfSort == System.Windows.Forms.SortOrder.Ascending)
                {
                    lvwColumnSorter.OrderOfSort = System.Windows.Forms.SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.OrderOfSort = System.Windows.Forms.SortOrder.Ascending;
                }
            }
            else
            {
                // 设置排序列，默认为正向排序
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.OrderOfSort = System.Windows.Forms.SortOrder.Ascending;
            }

            // 用新的排序方法对ListView排序
            (sender as System.Windows.Forms.ListView).Sort();
        }
    }

 	public class TExtWebClientData : Object
	{
        private string FPackageName, FBaseFormName, FServerPackageName, FFolderName, FTableName, FRealTableName, FFormName, FProviderName, 
            FDatabaseName, FSolutionName, FViewProviderName, FWebSiteName, FFolderMode, FFormTitle;
        private TBlockItems FBlocks;
        private MWizard.fmExtEEPWebWizard FOwner;
        private bool FNewSolution = false;
        private string FCodeFolderName;
        private int FColumnCount;
        private ClientType FDatabaseType;
        private String FConnString;
        private String FLanguage = "cs";
        private List<InfoDataSet> FDataSetList = null;
        private List<InfoBindingSource> FDataSourceList = null;

		public TExtWebClientData(MWizard.fmExtEEPWebWizard Owner)
		{
			FOwner = Owner;
			FBlocks = new TBlockItems(this);
            FDataSetList = new List<InfoDataSet>();
            FDataSourceList = new List<InfoBindingSource>();
        }

        public ClientType DatabaseType
        {
            get { return FDatabaseType; }
            set { FDatabaseType = value; }
        }

        public fmExtEEPWebWizard Owner
        {
            get { return FOwner; }
            set { FOwner = value; }
        }

        public String FormTitle
        {
            get { return FFormTitle; }
            set { FFormTitle = value; }
        }

        public String ConnString
        {
            get { return FConnString; }
            set { FConnString = value; }
        }

        public String Language
        {
            get { return FLanguage; }
            set { FLanguage = value; }
        }

        public List<InfoDataSet> DataSetList
        {
            get { return FDataSetList; }
        }

        public List<InfoBindingSource> DataSourceList
        {
            get { return FDataSourceList; }
        }

        public InfoBindingSource FindDataSource(String ID)
        {
            foreach (InfoBindingSource DataSource in FDataSourceList)
                if (DataSource.Site.Name.CompareTo(ID) == 0)
                    return DataSource;
            return null;
        }

        public InfoDataSet FindDataSet(String ID)
        {
            foreach (InfoDataSet aDataSet in FDataSetList)
            {
                if (aDataSet.Site.Name.CompareTo(ID) == 0)
                    return aDataSet;
            }
            return null;
        }

        public List<TBlockItem> FindBlockItemByDataSource(InfoBindingSource DataSource)
        {
            List<TBlockItem> Result = new List<TBlockItem>();
            foreach (TBlockItem BlockItem in Blocks)
            {
                if (BlockItem.BindingSource == DataSource)
                    Result.Add(BlockItem);
            }
            return Result;
        }

        private void LoadBlockFieldItems(XmlNode Node, TBlockFieldItems BlockFieldItems)
        {
            TBlockFieldItem BFI;
            int I;
            XmlNode BlockFieldItemNode;
            for (I = 0; I < Node.ChildNodes.Count; I++)
            {
                BlockFieldItemNode = Node.ChildNodes[I];
                BFI = new TBlockFieldItem();
                BFI.DataField = BlockFieldItemNode.Attributes["DataField"].Value;
                BFI.Description = BlockFieldItemNode.Attributes["Description"].Value;
                BFI.Length = int.Parse(BlockFieldItemNode.Attributes["Length"].Value.ToString());
                foreach (XmlNode RefNode in BlockFieldItemNode.ChildNodes)
                {
                    BFI.RefField = new TRefField();
                    BFI.RefField.SelectCommand = RefNode.Attributes["SelectCommand"].Value;
                    BFI.RefField.ValueMember = RefNode.Attributes["ValueMember"].Value;
                    BFI.RefField.DisplayMember = RefNode.Attributes["DisplayMember"].Value;
                    foreach (XmlNode ColumnNode in RefNode.ChildNodes)
                    {
                        RefColumns aColumn = new RefColumns();
                        aColumn.Column = ColumnNode.Attributes["Column"].Value;
                        aColumn.HeaderText = ColumnNode.Attributes["HeaderText"].Value;
                        aColumn.Width = int.Parse(ColumnNode.Attributes["Width"].Value);
                        BFI.RefField.LookupColumns.Add(aColumn);
                    }
                }
                //IPC保留缺口
                //BlockFieldItem.CheckNull = DR["CHECK_NULL"].ToString();
                //BlockFieldItem.DefaultValue = DR["DEFAULT_VALUE"].ToString();
                BlockFieldItems.Add(BFI);
            }
        }

        private void LoadBlocks(XmlNode Node)
        {
            int I;
            TBlockItem BI;
            XmlNode BlockNode, BlockFieldItemsNode;
            for (I = 0; I < Node.ChildNodes.Count; I++)
            {
                BlockNode = Node.ChildNodes[I];
                BI = new TBlockItem();
                BI.Name = BlockNode.Attributes["Name"].Value;
                BI.ProviderName = BlockNode.Attributes["ProviderName"].Value;
                BI.TableName = BlockNode.Attributes["TableName"].Value;
                BlockFieldItemsNode = WzdUtils.FindNode(null, BlockNode, "BlockFieldItems");
                LoadBlockFieldItems(BlockFieldItemsNode, BI.BlockFieldItems);
                Blocks.Add(BI);
            }
        }

        public object LoadFromXML(string XML)
        {
            System.Xml.XmlNode Node = null;
            System.Xml.XmlDocument Doc = new System.Xml.XmlDocument();
            Doc.LoadXml(XML);
            Node = Doc.SelectSingleNode("ClientData");
            SolutionName = Node.Attributes["SolutionName"].Value;
            NewSolution = Node.Attributes["NewSolution"].Value == "1";
            WebSiteName = Node.Attributes["PackageName"].Value;
            BaseFormName = Node.Attributes["BaseFormName"].Value;
            FolderName = Node.Attributes["FolderName"].Value;
            FolderMode = "ExistFolder";
            FormName = Node.Attributes["FormName"].Value;
            TableName = Node.Attributes["TableName"].Value;
            ProviderName = Node.Attributes["ProviderName"].Value;
            if (Node.Attributes["Language"].Value.ToString().CompareTo("C#") == 0)
                this.Language = "cs";
            else
                this.Language = "vb";
            Node = WzdUtils.FindNode(Doc, Node, "Blocks");
            LoadBlocks(Node);
            return null;
        }

		public bool IsMasterDetailBaseForm()
		{ 
			bool Result;
            Result = false;
            if (string.Compare(FBaseFormName, "WMasterDetail1") == 0 ||
                string.Compare(FBaseFormName, "WMasterDetail2") == 0 ||
                string.Compare(FBaseFormName, "WMasterDetail3") == 0 ||
                string.Compare(FBaseFormName, "VBWebCMasterDetail_FG") == 0 ||
                string.Compare(FBaseFormName, "VBWebCMasterDetail_DG") == 0 ||
                string.Compare(FBaseFormName, "VBWebCMasterDetail_VFG") == 0)
			{
				Result = true;
			}
			return Result;
   		}

        public bool NewSolution
        {
            get
            {
                return FNewSolution;
            }
            set
            {
                FNewSolution = value;
            }
        }

        public string SolutionName
        {
            get
            {
                return FSolutionName;
            }
            set
            {
                FSolutionName = value;
            }
        }

        public string ViewProviderName
        {
            get
            {
                return FViewProviderName;
            }
            set
            {
                FViewProviderName = value;
            }
        }

        public string WebSiteName
        {
            get
            {
                return FWebSiteName;
            }
            set
            {
                FWebSiteName = value;
            }
        }

        public string FolderMode
        {
            get
            {
                return FFolderMode;
            }
            set
            {
                FFolderMode = value;
            }
        }

		public string DatabaseName
		{
			get
			{
				return FDatabaseName;
			}
			set
			{
				FDatabaseName = value;
			}
		}

        public string PackageName
		{
			get
			{
				return FPackageName;
			}
			set
			{
				FPackageName = value;
			}

		}

		public string BaseFormName
		{
			get
			{
				return FBaseFormName;
			}
			set
			{
				FBaseFormName = value;
			}
		}

		public string ServerPackageName
		{
			get
			{
				return FServerPackageName;
			}
			set
			{
				FServerPackageName = value;
			}
		}

		public string FolderName
		{
			get
			{
                return FFolderName;
			}
			set
			{
                FFolderName = value;
			}

		}

        public string CodeFolderName
        {
            get
            {
                return FCodeFolderName;
            }
            set
            {
                string S = value;
                if (S != "")
                    if (S[S.Length - 1] == '\\')
                        S = S.Substring(0, S.Length - 1);
                FCodeFolderName = S;
            }
        }

        public int ColumnCount
        {
            get
            {
                return FColumnCount;
            }
            set
            {
                FColumnCount = value;
            }
        }

        public string TableName
		{
			get
			{
				return FTableName;
			}
			set
			{
				FTableName = value;
			}
		}

        public string RealTableName
        {
            get
            {
                return FRealTableName;
            }
            set
            {
                FRealTableName = value;
            }
        }

		public string FormName
		{
			get
			{
				return FFormName;
			}
			set
			{
				FFormName = value;
			}
		}

		public string ProviderName
		{
			get
			{
				return FProviderName;
			}
			set
			{
				FProviderName = value;
			}
		}

		public TBlockItems Blocks
		{
			get
			{
				return FBlocks;
			}
			set
			{
				FBlocks = value;
			}
		}
	}

	public class TExtWebClientGenerator : System.ComponentModel.Component
	{
        private TExtWebClientData FClientData;
		private DTE2 FDTE2;
        private AddIn FAddIn;
		private System.Windows.Forms.Form FRootForm = null;
		private System.ComponentModel.Design.IDesignerHost FDesignerHost;
        private WebDataSet FDataSet = null;
        private ProjectItem FPI;
        private Project FProject = null;
        private InfoDataGridView FViewGrid = null;
        private System.Web.UI.Page FPage;
        private String FResxFileName;
        private DataSet FSYS_REFVAL;
        private Window FDesignWindow;
        private List<WebDataSource> FWebDataSourceList;
        private List<WebRefVal> FWebRefValList;
        private List<WebDefault> FWebDefaultList;
        private List<WebValidate> FWebValidateList;
        private List<MyWebDropDownList> FMyWebDropDownList;
        private List<WebDateTimePicker> FWebDateTimePickerList;
        private List<WebValidateBox> FWebValidateBoxList;
        private List<System.Web.UI.WebControls.Label> FLabelList;
        private InfoDataSet FWizardDataSet = null;
#if VS90
        private WebDevPage.DesignerDocument FDesignerDocument;
#endif

        public TExtWebClientGenerator(TExtWebClientData ClientData, DTE2 dte2, AddIn aAddIn)
		{
			FClientData = ClientData;
			FDTE2 = dte2;
            FAddIn = aAddIn;
            FSYS_REFVAL = new DataSet();
            FWebDataSourceList = new List<WebDataSource>();
            FWebRefValList = new List<WebRefVal>();
            FWebDefaultList = new List<WebDefault>();
            FWebValidateList = new List<WebValidate>();
            FMyWebDropDownList = new List<MyWebDropDownList>();
            FWebDateTimePickerList = new List<WebDateTimePicker>();
            FWebValidateBoxList = new List<WebValidateBox>();
            FLabelList = new List<System.Web.UI.WebControls.Label>();
            //???FTemplatePath = Path.GetDirectoryName(FAddIn.Object.GetType().Assembly.Location) + "\\Templates\\";
		}

        private void GenFolder()
        {
            Solution2 sln = (Solution2)FDTE2.Solution;

            if (string.Compare(sln.FullName, FClientData.SolutionName) != 0)
            {
                sln.Open(FClientData.SolutionName);
            }
            foreach (Project P in sln.Projects)
            {
                if (String.Compare(P.Kind, "{E24C65DC-7377-472b-9ABA-BC803B73C61A}") == 0)
                {
                    String VSName = P.Name;
                    if (FClientData.Owner.SDCall)
                    {
                        VSName = WzdUtils.FixupToVSWebSiteName(VSName);
                    }
                    if (string.Compare(VSName, FClientData.WebSiteName) == 0)
                    {
                        FProject = P;
                        break;
                    }
                }
            }
            switch (FClientData.FolderMode)
            {
                case "ExistFolder":
                    foreach (ProjectItem PI in FProject.ProjectItems)
                    {
                        if (string.Compare(PI.Name, FClientData.FolderName) == 0)
                        {
                            FPI = PI;
                            break;
                        }
                    }
                    break;
                case "NewFolder":
                    FPI = FProject.ProjectItems.AddFolder(FClientData.FolderName, "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}");
                    break;
                default:
                    break;
            }
        }

        private bool GetForm()
        {
            String TemplatePath = EEPRegistry.WebClient + "\\Template";
            if (TemplatePath == "")
            {
                MessageBox.Show("Cannot find WebTemplate path: {0}", TemplatePath);
                return false;
            }
            if (FPI != null)
            {
                foreach (ProjectItem aPI in FPI.ProjectItems)
                {
                    if (string.Compare(FClientData.FormName + ".aspx", aPI.Name) == 0 ||
                        string.Compare(FClientData.FormName + ".aspx.resx", aPI.Name) == 0 ||
                        string.Compare(FClientData.FormName + ".aspx.vi-VN.resx", aPI.Name) == 0)
                    {
                        DialogResult dr = MessageBox.Show("There is another File which name is " + FClientData.PackageName + " existed! Do you want to delete it first", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (dr == DialogResult.Yes)
                        {
                            string Path = aPI.get_FileNames(0);

                            aPI.Name = Guid.NewGuid().ToString();
                            aPI.Open("{7651A702-06E5-11D1-8EBD-00A0C90F26EA}");
                            aPI.Delete();
                            File.Delete(Path);
                        }
                        else
                        {
                            return false;
                        }
                        continue;
                    }
                    if (string.Compare(FClientData.BaseFormName + ".aspx", aPI.Name) == 0 ||
                        string.Compare(FClientData.BaseFormName + ".aspx.resx", aPI.Name) == 0 ||
                        string.Compare(FClientData.BaseFormName + ".aspx.vi-VN.resx", aPI.Name) == 0)
                    {
                        string Path = aPI.get_FileNames(0);

                        aPI.Name = Guid.NewGuid().ToString();
                        aPI.Open("{7651A702-06E5-11D1-8EBD-00A0C90F26EA}");
                        aPI.Delete();
                        File.Delete(Path);
                    }
                }

                ProjectItem TempPI = FPI;
                FPI = FPI.ProjectItems.AddFromFileCopy(TemplatePath + "\\" + FClientData.BaseFormName + ".aspx");
                FPI.Name = FClientData.FormName + ".aspx";
                ProjectItem P1 = TempPI.ProjectItems.AddFromFileCopy(TemplatePath + "\\" + FClientData.BaseFormName + ".aspx.resx");
                P1.Name = FClientData.FormName + ".aspx.resx";
                ProjectItem P2 = TempPI.ProjectItems.AddFromFileCopy(TemplatePath + "\\" + FClientData.BaseFormName + ".aspx.vi-VN.resx");
                P2.Name = FClientData.FormName + ".aspx.vi-VN.resx";
                FResxFileName = P2.Name;
            }
            else
            {
                foreach (ProjectItem aPI in FProject.ProjectItems)
                {
                    if (string.Compare(FClientData.FormName + ".aspx", aPI.Name) == 0)
                    {
                        string Path = aPI.get_FileNames(0);
                        Path = System.IO.Path.GetDirectoryName(Path);
                        aPI.Delete();
                        if (System.IO.File.Exists(Path + "\\" + FClientData.FormName + ".aspx.resx"))
                            System.IO.File.Delete(Path + "\\" + FClientData.FormName + ".aspx.resx");
                        if (System.IO.File.Exists(Path + "\\" + FClientData.FormName + ".aspx.vi-VN.resx"))
                            System.IO.File.Delete(Path + "\\" + FClientData.FormName + ".aspx.vi-VN.resx");
                        break;
                    }
                }

                FPI = FProject.ProjectItems.AddFromFileCopy(TemplatePath + "\\" + FClientData.BaseFormName + ".aspx");
                FPI.Name = FClientData.FormName + ".aspx";
                ProjectItem P1 = FProject.ProjectItems.AddFromFileCopy(TemplatePath + "\\" + FClientData.BaseFormName + ".aspx.resx");
                P1.Name = FClientData.FormName + ".aspx.resx";
                ProjectItem P2 = FProject.ProjectItems.AddFromFileCopy(TemplatePath + "\\" + FClientData.BaseFormName + ".aspx.vi-VN.resx");
                P2.Name = FClientData.FormName + ".aspx.vi-VN.resx";
            }

            return true;
        }

        private void GetDesignerHost()
        {
#if VS90
            //FDesignWindow = FPI.Open("{00000000-0000-0000-0000-000000000000}");
            //FDesignWindow.Activate();

            FDesignWindow = FPI.Open("{7651A702-06E5-11D1-8EBD-00A0C90F26EA}");
            FDesignWindow.Activate();

            HTMLWindow W = (HTMLWindow)FDesignWindow.Object;

            //W.CurrentTab = vsHTMLTabs.vsHTMLTabsSource;
            //if (W.CurrentTabObject is TextWindow)
            //    FTextWindow = W.CurrentTabObject as TextWindow;
            W.CurrentTab = vsHTMLTabs.vsHTMLTabsDesign;
            if (W.CurrentTabObject is WebDevPage.DesignerDocument)
            {
                FDesignerDocument = W.CurrentTabObject as WebDevPage.DesignerDocument; 
            }
#else
            FDesignWindow = FPI.Open("{00000000-0000-0000-0000-000000000000}");
            FDesignWindow.Activate();
            FDesignWindow = FPI.Open("{7651A702-06E5-11D1-8EBD-00A0C90F26EA}");
            FDesignWindow.Activate();
            //FHtmlDocument = (HtmlDocument)aW.Document;
            HTMLWindow W = (HTMLWindow)FDesignWindow.Object;
            object o = W.CurrentTabObject;
            IntPtr pObject;
            Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSP = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)o;
            Guid sid = typeof(IVSMDDesigner).GUID;
            Guid iid = typeof(IVSMDDesigner).GUID;
            int hr = oleSP.QueryService(ref sid, ref iid, out pObject);
            System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr);
            if (pObject != IntPtr.Zero)
            {
                try
                {
                    Object TempObj = Marshal.GetObjectForIUnknown(pObject);
                    if (TempObj is IDesignerHost)
                    {
                        FDesignerHost = (IDesignerHost)TempObj;
                    }
                    else
                    {
                        Object ObjContainer = TempObj.GetType().InvokeMember("ComponentContainer",
                            System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public |
                            System.Reflection.BindingFlags.GetProperty, null, TempObj, null);
                        if (ObjContainer is IDesignerHost)
                        {
                            FDesignerHost = (IDesignerHost)ObjContainer;
                        }
                    }
                    FPage = (System.Web.UI.Page)FDesignerHost.RootComponent;
                    Application.DoEvents();
                    //FPage.Form.ID = FClientData.FormName;
                }
                finally
                {
                    Marshal.Release(pObject);
                }
            }
#endif
        }

        private void GenResx(TBlockItem BlockItem)
        {
            WebDataSet aWebDataSet = FDesignerHost.CreateComponent(typeof(WebDataSet), BlockItem.BindingSource.text) as WebDataSet;
            WebDataSet bWebDataSet = FDesignerHost.CreateComponent(typeof(WebDataSet), "WView") as WebDataSet;
            try
            {
                aWebDataSet.SetWizardDesignMode(true);
                aWebDataSet.RemoteName = FClientData.FindDataSet(BlockItem.BindingSource.text).RemoteName;
                aWebDataSet.PacketRecords = 100;
                aWebDataSet.Active = true;

                if (FClientData.ViewProviderName != null && FClientData.ViewProviderName != String.Empty)
                {
                    bWebDataSet.RemoteName = FClientData.ViewProviderName;
                    bWebDataSet.PacketRecords = 0;
                    bWebDataSet.Active = true;
                }

                MyDesingerLoader ML = new MyDesingerLoader(FClientData.FolderName + @"\" + FResxFileName);
                FDesignerHost.AddService(typeof(IResourceService), ML);
                WebDataSetDesigner aDesigner = (WebDataSetDesigner)FDesignerHost.GetDesigner(aWebDataSet);

                aDesigner.Initialize(aWebDataSet);
                if (aDesigner != null)
                {
                    aDesigner.OnSave(FDesignWindow.Document, null);
                }

                WebDataSourceDesigner aWebDataSourceDesigner = FDesignerHost.GetDesigner(FindWebDataSource(BlockItem)) as WebDataSourceDesigner;
                if (aWebDataSourceDesigner != null)
                {
                    aWebDataSourceDesigner.RefreshSchema(true);
                }
            }
            finally
            {
                aWebDataSet.Dispose();
            }
        }

        private WebDataSource GenWebDataSource(TBlockFieldItem FieldItem, String TableName, String Kind, String ExtraName)
        {
            String Name = "wds" + TableName + FieldItem.DataField + ExtraName;
            foreach (WebDataSource bWebDataSource in FWebDataSourceList)
            {
                if (String.Compare(bWebDataSource.ID, Name) == 0)
                {
                    return bWebDataSource;
                }
            }

            WebDataSource aWebDataSource = new WebDataSource();
            InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
            aInfoCommand.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
            //aInfoCommand.Connection = FClientData.Owner.GlobalConnection;
            IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
            //SYS_REFVAL
#if VS90
            WebDevPage.IHTMLElement form = ((WebDevPage.IHTMLElementCollection)FDesignerDocument.pageContentElement.children).item("form1", 0) as WebDevPage.IHTMLElement;
            if (Kind == "RefVal")
            {
                if (FSYS_REFVAL != null)
                    FSYS_REFVAL.Dispose();
                FSYS_REFVAL = new DataSet();
                aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL where REFVAL_NO = '{0}'", FieldItem.RefValNo);
                WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, FSYS_REFVAL, FieldItem.RefValNo);
                aWebDataSource.SelectAlias = FSYS_REFVAL.Tables[0].Rows[0]["SELECT_ALIAS"].ToString();
                aWebDataSource.SelectCommand = FSYS_REFVAL.Tables[0].Rows[0]["SELECT_COMMAND"].ToString();

                form.insertAdjacentHTML("afterBegin", "<InfoLight:WebDataSource ID=\"" + Name + "\" runat=\"server\" SelectAlias=\"" + aWebDataSource.SelectAlias + "\" SelectCommand=\"" + aWebDataSource.SelectCommand + "\"></InfoLight:WebDataSource>");
            }
            //WebDropDownList
            if (Kind == "ComboBox")
            {
                string type = FindSystemDBType("SystemDB");

                aWebDataSource.SelectAlias = FClientData.Owner.SelectedAlias;
                if (type == "1")
                    aWebDataSource.SelectCommand = String.Format("Select * from [{0}]", TableName);
                else if (type == "2")
                    aWebDataSource.SelectCommand = String.Format("Select * from [{0}]", TableName);
                else if (type == "3")
                    aWebDataSource.SelectCommand = String.Format("Select * from {0}", TableName);
                else if (type == "4")
                    aWebDataSource.SelectCommand = String.Format("Select * from {0}", TableName);
                else if (type == "5")
                    aWebDataSource.SelectCommand = String.Format("Select * from {0}", TableName);
                else if (type == "6")
                    aWebDataSource.SelectCommand = String.Format("Select * from {0}", TableName);

                form.insertAdjacentHTML("afterBegin", "<InfoLight:WebDataSource ID=\"" + Name + "\" runat=\"server\" SelectAlias=\"" + FClientData.Owner.SelectedAlias + "\" SelectCommand=\"" + aWebDataSource.SelectCommand + "\"></InfoLight:WebDataSource>");
            }
#else
            if (Kind == "RefVal")
            {
                if (FSYS_REFVAL != null)
                    FSYS_REFVAL.Dispose();
                FSYS_REFVAL = new DataSet();
                aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL where REFVAL_NO = '{0}'", FieldItem.RefValNo);
                WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, FSYS_REFVAL, FieldItem.RefValNo);
                aWebDataSource.SelectAlias = FSYS_REFVAL.Tables[0].Rows[0]["SELECT_ALIAS"].ToString();
                aWebDataSource.SelectCommand = FSYS_REFVAL.Tables[0].Rows[0]["SELECT_COMMAND"].ToString();
            }
            //WebDropDownList
            if (Kind == "ComboBox")
            {
                string type = FindSystemDBType("SystemDB");

                aWebDataSource.SelectAlias = FClientData.Owner.SelectedAlias;
                if (type == "1")
                    aWebDataSource.SelectCommand = String.Format("Select * from [{0}]", TableName);
                else if (type == "2")
                    aWebDataSource.SelectCommand = String.Format("Select * from [{0}]", TableName);
                else if (type == "3")
                    aWebDataSource.SelectCommand = String.Format("Select * from {0}", TableName);
                else if (type == "4")
                    aWebDataSource.SelectCommand = String.Format("Select * from {0}", TableName);
                else if (type == "5")
                    aWebDataSource.SelectCommand = String.Format("Select * from {0}", TableName);
            }
#endif
            aWebDataSource.ID = Name;
            if (!FWebDataSourceList.Contains(aWebDataSource))
            {
                FWebDataSourceList.Add(aWebDataSource);
            }
            return aWebDataSource;
        }

        public String FindSystemDBType(String aliasName)
        {
            String xmlName = SystemFile.DBFile;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlName);

            XmlNode node = xmlDoc.FirstChild.SelectSingleNode(aliasName);

            string DbString = node.FirstChild.Value;
            string systemDBType = FindDBType(DbString);

            return systemDBType;
        }

        public String FindDBType(String aliasName)
        {
            String xmlName = SystemFile.DBFile;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlName);

            XmlNode node = xmlDoc.FirstChild.FirstChild.SelectSingleNode(aliasName);

            string DbType = node.Attributes["Type"].Value.Trim();
            return DbType;
        }

        private void TestCreateSomething()
        {
            //IWebFormReferenceManager aManager = FDesignerHost.GetService(typeof(IWebFormReferenceManager)) as IWebFormReferenceManager;

            //System.Web.UI.WebControls.Button TB = FDesignerHost.CreateComponent(typeof(System.Web.UI.WebControls.Button), "TextBBB") as System.Web.UI.WebControls.Button;
            //FPage.Controls.Add(TB);
            //ToolboxDataAttribute attribute = TypeDescriptor.GetAttributes(typeof(System.Web.UI.WebControls.Button))[typeof(ToolboxDataAttribute)] as ToolboxDataAttribute;

            //ControlDesigner A = FDesignerHost.GetDesigner(TB) as ControlDesigner;

            //if (attribute != null)
            //{
            //    ((IHTMLElement)A.Behavior.DesignTimeElement).insertAdjacentHTML(
            //    "beforeEnd", String.Format(attribute.Data, aManager.GetTagPrefix(typeof(
            //    Content))));
            //}
            //else
            //{
            //    ((IHTMLElement)A.Behavior.DesignTimeElement).insertAdjacentHTML(
            //    "beforeEnd", String.Format("<{0}:Button runat='server'></{0}:Button>",
            //    aManager.GetTagPrefix(typeof(Content))));
            //}
        }

        private void GenDefault(TBlockFieldItem aFieldItem, WebDefault aDefault, WebValidate aValidate)
        {
            if (aDefault != null && aFieldItem.DefaultValue != "" && aFieldItem.DefaultValue != null)
            {
                DefaultFieldItem aDefaultItem = new DefaultFieldItem();
                aDefaultItem.FieldName = aFieldItem.DataField;
                aDefaultItem.DefaultValue = aFieldItem.DefaultValue;
                aDefault.Fields.Add(aDefaultItem);
            }
            if (aValidate != null && aFieldItem.CheckNull != null && aFieldItem.CheckNull.ToUpper() == "Y")
            {
                ValidateFieldItem aValidateItem = new ValidateFieldItem();
                aValidateItem.FieldName = aFieldItem.DataField;
                aValidateItem.CheckNull = aFieldItem.CheckNull.ToUpper() == "Y";
                aValidateItem.ValidateLabelLink = "Caption" + aFieldItem.DataField;
                aValidate.Fields.Add(aValidateItem);
            }
        }

        private void CreateQueryField(TBlockFieldItem aFieldItem, String Range, InfoComboBox aComboBox, String TableName)
        {
            if (aFieldItem.QueryMode == null)
                return;
            WebNavigator navigator2 = FPage.FindControl("WebNavigator1") as WebNavigator;
            if (navigator2 != null)
            {
                if (aFieldItem.QueryMode.ToUpper() == "NORMAL" || aFieldItem.QueryMode.ToUpper() == "RANGE")
                {
                    WebQueryField qField = new WebQueryField();
                    qField.FieldName = aFieldItem.DataField;
                    qField.Caption = aFieldItem.Description;
                    if (qField.Caption == "")
                        qField.Caption = aFieldItem.DataField;
                    if (aFieldItem.QueryMode.ToUpper() == "NORMAL")
                    {
                        if (aFieldItem.DataType == typeof(DateTime))
                            qField.Condition = "=";
                        if (aFieldItem.DataType == typeof(int) || aFieldItem.DataType == typeof(float) ||
                            aFieldItem.DataType == typeof(double) || aFieldItem.DataType == typeof(Int16))
                            qField.Condition = "=";
                        if (aFieldItem.DataType == typeof(String))
                            qField.Condition = "%";
                    }
                    if (aFieldItem.QueryMode.ToUpper() == "RANGE")
                    {
                        if (Range == "")
                        {
                            qField.Condition = "<=";
                            CreateQueryField(aFieldItem, ">=", aComboBox, TableName);
                        }
                        else
                        {
                            qField.Condition = Range;
                        }
                    }
                    switch (aFieldItem.ControlType.ToUpper())
                    {
                        case "TEXTBOX":
                            qField.Mode = "TextBox";
                            break;
                        case "COMBOBOX":
                            qField.Mode = "ComboBox";
                            qField.RefVal = "wrv" + TableName + aFieldItem.DataField + "QF";
                            break;
                        case "REFVALBOX":
                            qField.Mode = "RefVal";
                            qField.RefVal = "wrv" + TableName + aFieldItem.DataField + "QF";
                            break;
                        case "DATETIMEBOX":
                            qField.Mode = "Calendar";
                            break;
                    }
                    navigator2.QueryFields.Add(qField);
                }
                IComponentChangeService aComponentChangeService = (IComponentChangeService)FDesignerHost.RootComponent.Site.GetService(typeof(IComponentChangeService));
                aComponentChangeService.OnComponentChanged(navigator2, null, "", "M");
            }

            WebClientQuery WebClientQuery1 = (WebClientQuery)FPage.FindControl("WebClientQuery1");
            if (WebClientQuery1 != null)
            {
                if (aFieldItem.QueryMode.ToUpper() == "NORMAL" || aFieldItem.QueryMode.ToUpper() == "RANGE")
                {
                    WebQueryColumns qColumns = new WebQueryColumns();
                    qColumns.Column = aFieldItem.DataField;
                    qColumns.Caption = aFieldItem.Description;
                    if (qColumns.Caption == "")
                        qColumns.Caption = aFieldItem.DataField;
                    qColumns.Condition = "And";
                    if (aFieldItem.QueryMode.ToUpper() == "NORMAL")
                    {
                        if (aFieldItem.DataType == typeof(DateTime))
                            qColumns.Operator = "=";
                        if (aFieldItem.DataType == typeof(int) || aFieldItem.DataType == typeof(float) ||
                            aFieldItem.DataType == typeof(double) || aFieldItem.DataType == typeof(Int16))
                            qColumns.Operator = "=";
                        if (aFieldItem.DataType == typeof(String))
                            qColumns.Operator = "%";
                    }
                    if (aFieldItem.QueryMode.ToUpper() == "RANGE")
                    {
                        qColumns.Condition = "And";
                        if (Range == "")
                        {
                            qColumns.Operator = "<=";
                            CreateQueryField(aFieldItem, ">=", aComboBox, TableName);
                        }
                        else
                        {
                            qColumns.Operator = Range;
                        }
                    }
                    switch (aFieldItem.ControlType.ToUpper())
                    {
                        case "TEXTBOX":
                            qColumns.ColumnType = "ClientQueryTextBoxColumn";
                            break;
                        case "COMBOBOX":
                            qColumns.ColumnType = "ClientQueryComboBoxColumn";
                            qColumns.WebRefVal = "wrv" + TableName + aFieldItem.DataField + "QF";
                            break;
                        case "REFVALBOX":
                            qColumns.ColumnType = "ClientQueryRefValColumn";
                            qColumns.WebRefVal = "wrv" + TableName + aFieldItem.DataField + "QF";
                            break;
                        case "DATETIMEBOX":
                            qColumns.ColumnType = "ClientQueryCalendarColumn";
                            break;
                        case "CHECKBOX":
                            qColumns.ColumnType = "ClientQueryCheckBoxColumn";
                            break;
                    }
                    WebClientQuery1.Columns.Add(qColumns);
                }
                IComponentChangeService FComponentChangeService = (IComponentChangeService)FDesignerHost.RootComponent.Site.GetService(typeof(IComponentChangeService));
                FComponentChangeService.OnComponentChanged(WebClientQuery1, null, "", "M");
            }
        }

        private void GenWebDetailsViewBlock(TBlockItem BlockItem)
        {
#if VS90
            this.FClientData.TableName = BlockItem.TableName;
            InfoBindingSource aDataSource = FClientData.FindDataSource(BlockItem.BindingSource.Site.Name);
            object oMaster = FDesignerDocument.webControls.item(aDataSource.Site.Name, 0);

            WebDevPage.IHTMLElement eMaster = null;
            WebDevPage.IHTMLElement eWebDetailView1 = null;

            if (oMaster == null || !(oMaster is WebDevPage.IHTMLElement))
                return;
            eMaster = (WebDevPage.IHTMLElement)oMaster;
            eMaster.setAttribute("AutoApply", "true", 0);

            BlockItem.wDataSource = new WebDataSource();
            if (eMaster != null)
            {
                eMaster.setAttribute("DataMember", aDataSource.DataMember, 0);
            }

            WebDefault Default = null;
            if (!allDefaults.Contains("wd" + BlockItem.ProviderName))
            {
                Default = new WebDefault();
                Default.ID = "wd" + BlockItem.ProviderName;
                Default.DataSourceID = eMaster.getAttribute("ID", 0).ToString();
                Default.DataMember = aDataSource.DataMember;
            }

            WebValidate Validate = null;
            if (!allValidates.Contains("wv" + BlockItem.ProviderName))
            {
                Validate = new WebValidate();
                Validate.ID = "wv" + BlockItem.ProviderName;
                Validate.DataSourceID = eMaster.getAttribute("ID", 0).ToString();
                Validate.DataMember = aDataSource.DataMember;
            }

            WebQueryFiledsCollection QueryFields = new WebQueryFiledsCollection(null, typeof(QueryField));
            WebQueryColumnsCollection QueryColumns = new WebQueryColumnsCollection(null, typeof(QueryColumns));
            foreach (TBlockFieldItem fielditem in BlockItem.BlockFieldItems)
            {
                GenDefault(fielditem, Default, Validate);
                GenQuery(fielditem, QueryFields, QueryColumns, BlockItem.ProviderName);
            }

            WebDevPage.IHTMLElement Page = FDesignerDocument.pageContentElement;
            if (Default != null)
                InsertControl(Page, Default);
            if (Validate != null)
                InsertControl(Page, Validate);

            foreach (TBlockFieldItem fielditem in BlockItem.BlockFieldItems)
            {
                foreach (WebQueryColumns wqc in QueryColumns)
                {
                    if (wqc.ColumnType == "ClientQueryRefValColumn" && wqc.Column == fielditem.DataField && fielditem.RefValNo != String.Empty)
                    {
                        WebDataSource aWebDataSource = new WebDataSource();
                        InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
                        aInfoCommand.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
                        //aInfoCommand.Connection = FClientData.Owner.GlobalConnection;
                        IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
                        if (FSYS_REFVAL != null)
                            FSYS_REFVAL.Dispose();
                        FSYS_REFVAL = new DataSet();
                        aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL where REFVAL_NO = '{0}'", fielditem.RefValNo);
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, FSYS_REFVAL, fielditem.RefValNo);

                        WebRefVal aWebRefVal = new WebRefVal();
                        aWebRefVal.ID = wqc.WebRefVal;
                        aWebRefVal.DataTextField = FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString();
                        aWebRefVal.DataValueField = FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString();
                        aWebRefVal.DataSourceID = String.Format("wds{0}{1}", BlockItem.ProviderName, wqc.Column);
                        aWebRefVal.Visible = false;
                        InsertControl(Page, aWebRefVal);
                        break;
                    }
                }
            }

            WebDevPage.IHTMLElement Navigator = (WebDevPage.IHTMLElement)FDesignerDocument.webControls.item("WebNavigator1", 0);
            if (Navigator != null)
            {
                SetCollectionValue(Navigator, typeof(WebNavigator).GetProperty("QueryFields"), QueryFields);
            }
            WebDevPage.IHTMLElement ClientQuery = (WebDevPage.IHTMLElement)FDesignerDocument.webControls.item("WebClientQuery1", 0);
            if (ClientQuery != null)
            {
                SetCollectionValue(ClientQuery, typeof(WebClientQuery).GetProperty("Columns"), QueryColumns);
            }

            object oWebDetailView1 = FDesignerDocument.webControls.item(BlockItem.ContainerName, 0);
            eWebDetailView1 = (WebDevPage.IHTMLElement)oWebDetailView1;
            //eWebDetailView1.setAttribute("DataMember", aDataSource.DataMember, 0);
            //这里本来想再往下找Columns节点的,可是找不到,只能先这样写了
            StringBuilder sb = new StringBuilder(eWebDetailView1.innerHTML);
            int idx = eWebDetailView1.innerHTML.IndexOf("<EmptyDataRowStyle ForeColor=\"Black\" />");
            sb.Insert(idx, "<Fields>\r\n            </Fields>\r\n            ");
            eWebDetailView1.innerHTML = sb.ToString();
            idx = eWebDetailView1.innerHTML.IndexOf("</Fields>");
            List<string> KeyFields = new List<string>();
            foreach (TBlockFieldItem BFI in BlockItem.BlockFieldItems)
            {
                idx = sb.ToString().IndexOf("</Fields>");
                if (!string.IsNullOrEmpty(BFI.RefValNo) || BFI.RefField != null)
                {
                    sb.Insert(idx, GenDetailViewTemplateFieldHTML(BFI.ControlType, BlockItem, BFI));
                }
                else if (BFI.ControlType == "ComboBox" || BFI.ControlType == "ValidateBox" || BFI.ControlType == "CheckBox")
                {
                    sb.Insert(idx, GenDetailViewTemplateFieldHTML(BFI.ControlType, BlockItem, BFI));
                }
                else
                {
                    if (BFI.DataType == typeof(DateTime) || (BFI.ControlType != null && BFI.ControlType == "DateTimeBox"))
                    {
                        sb.Insert(idx, GenDetailViewTemplateFieldHTML("DateTimeBox", BlockItem, BFI));
                    }
                    else
                    {
                        sb.Insert(idx, "\r            <asp:BoundField DataField=\"" + BFI.DataField + "\" HeaderText=\"" + (string.IsNullOrEmpty(BFI.Description) ? BFI.DataField : BFI.Description) + "\" SortExpression=\"" + BFI.DataField + "\" />\r\n            ");
                    }
                }
            }
            eWebDetailView1.innerHTML = sb.ToString();
#else
            WebDataSource Master = FindWebDataSource(BlockItem);
            WebDetailsView wdvMaster = (WebDetailsView)FPage.FindControl(BlockItem.ContainerName);

            //Generate RESX
            //???GenResx(Master);

            //wdvMaster.DataMember = BlockItem.ProviderName;
            wdvMaster.DataSourceID = Master.ID;
            //???WebGridView1.Columns.Clear();
            System.Web.UI.WebControls.BoundField aBoundField = null;
            System.Web.UI.WebControls.TemplateField aTemplateField = null;
            WebDefault aDefault = new WebDefault();
            aDefault.ID = "wd" + BlockItem.ProviderName;
            aDefault.DataSourceID = Master.ID;
            aDefault.DataMember = Master.DataMember;
            WebValidate aValidate = new WebValidate();
            aValidate.ID = "wv" + BlockItem.ProviderName;
            aValidate.DataSourceID = Master.ID;
            aValidate.DataMember = Master.DataMember;
            List<string> KeyFields = new List<string>();
            foreach (TBlockFieldItem BFI in BlockItem.BlockFieldItems)
            {
                if ((BFI.RefValNo != null && BFI.RefValNo != "") || BFI.RefField != null)
                {
                    String DataSourceID = GenWebDataSource(BFI, BlockItem.ProviderName, "RefVal", "").ID;
                    aTemplateField = new System.Web.UI.WebControls.TemplateField();
                    aTemplateField.HeaderText = BFI.Description;
                    aTemplateField.SortExpression = BFI.DataField;
                    if (aTemplateField.HeaderText == "")
                        aTemplateField.HeaderText = BFI.DataField;
                    aTemplateField.EditItemTemplate = new WebControlTemplate("WebGridViewRefValEditItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FClientData.Owner.GlobalConnection, FWebRefValList, FClientData.DatabaseType, null);
                    aTemplateField.ItemTemplate = new WebControlTemplate("WebGridViewRefValItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FClientData.Owner.GlobalConnection, FWebRefValList, FClientData.DatabaseType, null);
                    aTemplateField.InsertItemTemplate = new WebControlTemplate("DetailsViewRefValInsertItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FClientData.Owner.GlobalConnection, FWebRefValList, FClientData.DatabaseType, null);
                    wdvMaster.Fields.Add(aTemplateField);
                }
                else if (BFI.ControlType == "ComboBox")
                {
                    String DataSourceID = GenWebDataSource(BFI, BFI.ComboTableName, "ComboBox", "").ID;
                    aTemplateField = new System.Web.UI.WebControls.TemplateField();
                    aTemplateField.HeaderText = BFI.Description;
                    aTemplateField.SortExpression = BFI.DataField;
                    if (aTemplateField.HeaderText == "")
                        aTemplateField.HeaderText = BFI.DataField;
                    aTemplateField.EditItemTemplate = new WebControlTemplate("WebGridViewComboBoxEditItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FMyWebDropDownList, FLabelList);
                    aTemplateField.ItemTemplate = new WebControlTemplate("WebGridViewComboBoxItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FMyWebDropDownList, FLabelList);
                    aTemplateField.FooterTemplate = new WebControlTemplate("WebGridViewComboBoxFooterItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FMyWebDropDownList, FLabelList);
                    aTemplateField.InsertItemTemplate = new WebControlTemplate("DetailsViewComboBoxInsertItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FMyWebDropDownList, FLabelList);
                    wdvMaster.Fields.Add(aTemplateField);
                }
                else if (BFI.ControlType == "ValidateBox")
                {
                    aTemplateField = new System.Web.UI.WebControls.TemplateField();
                    aTemplateField.HeaderText = BFI.Description;
                    aTemplateField.SortExpression = BFI.DataField;
                    if (aTemplateField.HeaderText == "")
                        aTemplateField.HeaderText = BFI.DataField;
                    aTemplateField.EditItemTemplate = new WebControlTemplate("WebGridViewValidateBoxEditItemTemplate", BFI, BlockItem.ProviderName, aValidate, FWebValidateBoxList, FLabelList);
                    aTemplateField.InsertItemTemplate = new WebControlTemplate("DetailsViewValidateBoxInsertItemTemplate", BFI, BlockItem.ProviderName, aValidate, FWebValidateBoxList, FLabelList);
                    aTemplateField.ItemTemplate = new WebControlTemplate("WebGridViewValidateBoxItemTemplate", BFI, BlockItem.ProviderName, aValidate, FWebValidateBoxList, FLabelList);
                    aTemplateField.FooterTemplate = new WebControlTemplate("WebGridViewValidateBoxInsertItemTemplate", BFI, BlockItem.ProviderName, aValidate, FWebValidateBoxList, FLabelList);
                    wdvMaster.Fields.Add(aTemplateField);
                }
                else
                {
                    if (BFI.DataType == typeof(DateTime) || (BFI.ControlType != null && BFI.ControlType.ToUpper() == "DATETIMEBOX"))
                    {
                        aTemplateField = new System.Web.UI.WebControls.TemplateField();
                        aTemplateField.HeaderText = BFI.Description;
                        aTemplateField.SortExpression = BFI.DataField;
                        if (aTemplateField.HeaderText == "")
                            aTemplateField.HeaderText = BFI.DataField;
                        aTemplateField.EditItemTemplate = new WebControlTemplate("WebGridViewDateTimeEditItemTemplate", BFI, BlockItem.ProviderName, FWebDateTimePickerList, FLabelList);
                        aTemplateField.ItemTemplate = new WebControlTemplate("WebGridViewDateTimeItemTemplate", BFI, BlockItem.ProviderName, FWebDateTimePickerList, FLabelList);
                        aTemplateField.FooterTemplate = new WebControlTemplate("WebGridViewDateTimeFooterItemTemplate", BFI, BlockItem.ProviderName, FWebDateTimePickerList, FLabelList);
                        aTemplateField.InsertItemTemplate = new WebControlTemplate("DetailsViewDateTimeInsertItemTemplate", BFI, BlockItem.ProviderName, FWebDateTimePickerList, FLabelList);
                        wdvMaster.Fields.Add(aTemplateField);
                    }
                    else
                    {
                        aBoundField = new System.Web.UI.WebControls.BoundField();
                        aBoundField.DataField = BFI.DataField;
                        aBoundField.SortExpression = BFI.DataField;
                        aBoundField.HeaderText = BFI.Description;
                        aBoundField.HeaderStyle.Width = 150;//BFI.Length * ColumnWidthPixel;
                        if (aBoundField.HeaderText == "")
                            aBoundField.HeaderText = BFI.DataField;
                        wdvMaster.Fields.Add(aBoundField);
                    }
                }

                if (BFI.IsKey)
                    KeyFields.Add(BFI.DataField);

                CreateQueryField(BFI, "", null, BlockItem.ProviderName);

                GenDefault(BFI, aDefault, aValidate);
            }

            InfoDataSet aDataSet = FClientData.FindDataSet(BlockItem.BindingSource.text);
            DataTable DT = aDataSet.RealDataSet.Tables[0];
            DataColumn[] PrimDc = DT.PrimaryKey;
            string[] AA = new string[PrimDc.Length];
            for (int J = 0; J < PrimDc.Length; J++)
                AA[J] = PrimDc[J].ColumnName;
            /*
            wdvMaster.DataKeyNames = new string[AA.Length];
            for (int I = 0; I < AA.Length; I++)
            {
                wdvMaster.DataKeyNames[I] = AA[I];
            }
             */
            FWebDefaultList.Add(aDefault);
            FWebValidateList.Add(aValidate);
            IComponentChangeService FComponentChangeService = (IComponentChangeService)FDesignerHost.RootComponent.Site.GetService(typeof(IComponentChangeService));
            FComponentChangeService.OnComponentChanged(wdvMaster, null, "", "M");
#endif
        }

        private string GetValidateText(string ControlText)
        {
            string fieldName = ControlText;

            int Index = ControlText.IndexOf("Bind(\"");
            if (Index > -1)
            {
                fieldName = ControlText.Substring(Index + 6);
                fieldName = fieldName.Substring(0, fieldName.IndexOf("\""));
            }

            return fieldName;
        }

        private string GetDDText(string ControlText, TBlockItem BlockItem, String TemplateName)
        {
            int Index1 = ControlText.IndexOf("Bind(\"");
            if (Index1 < 0)
            {
                foreach (TBlockFieldItem FieldItem in BlockItem.BlockFieldItems)
                { 
                    if (String.Compare(ControlText, FieldItem.DataField) == 0)
                    {
                        // <asp:Label ID="CaptionGROUPID" runat="server" Text="群組編號:"></asp:Label>
                        String Description = FieldItem.Description;
                        if (Description == null || Description == "")
                            Description = FieldItem.DataField;
                        String ExtraName = "";
                        if (TemplateName == "ItemTemplate")
                            ExtraName = "I";
                        return String.Format("<asp:Label ID=\"Caption{0}\" runat=\"server\" Text=\"{1}:\"></asp:Label>",
                            ExtraName + FieldItem.DataField, Description);
                    }
                }
                return ControlText + ":";
            }
            else
            {
                return ControlText;
            }
        }

        private System.Web.UI.WebControls.WebControl FindContainer(Object ParentControl, String ControlName)
        {
            WebControl Result = null;
            if (ParentControl is Page)
                Result = ((Page)ParentControl).FindControl(ControlName) as WebControl;
            if (Result == null)
            {
                if (ParentControl is Page)
                {
                    foreach (Object ChildControl in ((Page)ParentControl).Controls)
                    {
                        Result = FindContainer(ChildControl, ControlName);
                        if (Result != null)
                            return Result;
                    }
                }
                else
                {
                    foreach (Object ChildControl in ((WebControl)ParentControl).Controls)
                    {
                        Result = FindContainer(ChildControl, ControlName);
                        if (Result != null)
                            return Result;
                    }
                }
            }
            return Result;
        }

        private WebDataSource FindWebDataSource(TBlockItem BlockItem)
        {
            WebDataSource Result = null;
            Result = FPage.FindControl(BlockItem.BindingSource.Site.Name) as WebDataSource;
            return Result;
        }

        private void GenWebFormViewBlock(TBlockItem BlockItem)
        {
#if VS90
            InfoBindingSource aDataSource = FClientData.FindDataSource(BlockItem.BindingSource.Site.Name);

            this.FClientData.TableName = aDataSource.Tablename;
            WebDevPage.IHTMLElement Master = (WebDevPage.IHTMLElement)FDesignerDocument.webControls.item(aDataSource.Site.Name, 0);
            if (Master != null)
            {
                Master.setAttribute("DataMember", aDataSource.DataMember, 0);
                if (aDataSource.Site.Name == "wfvMaster")
                {
                    Master.setAttribute("AutoApply", "true", 0);
                }
            }
            BlockItem.wDataSource = new WebDataSource();

            WebDefault Default = null;
            if (!allDefaults.Contains("wd" + BlockItem.ProviderName))
            {
                Default = new WebDefault();
                Default.ID = "wd" + BlockItem.ProviderName;
                Default.DataSourceID = Master.getAttribute("ID", 0).ToString();
                Default.DataMember = aDataSource.DataMember;

                allDefaults.Add(Default.ID);
            }

            WebValidate Validate = null;
            if (!allValidates.Contains("wv" + BlockItem.ProviderName))
            {
                Validate = new WebValidate();
                Validate.ID = "wv" + BlockItem.ProviderName;
                Validate.DataSourceID = Master.getAttribute("ID", 0).ToString();
                Validate.DataMember = aDataSource.DataMember;

                allValidates.Add(Validate.ID);
            }

            WebQueryFiledsCollection QueryFields = new WebQueryFiledsCollection(null, typeof(QueryField));
            WebQueryColumnsCollection QueryColumns = new WebQueryColumnsCollection(null, typeof(QueryColumns));
            foreach (TBlockFieldItem fielditem in BlockItem.BlockFieldItems)
            {
                GenDefault(fielditem, Default, Validate);
                GenQuery(fielditem, QueryFields, QueryColumns, BlockItem.ProviderName);
            }

            WebDevPage.IHTMLElement Page = FDesignerDocument.pageContentElement;
            if (Default != null)
                InsertControl(Page, Default);
            if (Validate != null)
                InsertControl(Page, Validate);

            foreach (TBlockFieldItem fielditem in BlockItem.BlockFieldItems)
            {
                foreach (WebQueryColumns wqc in QueryColumns)
                {
                    if (wqc.ColumnType == "ClientQueryRefValColumn" && wqc.Column == fielditem.DataField && fielditem.RefValNo != String.Empty)
                    {
                        WebDataSource aWebDataSource = new WebDataSource();
                        InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
                        aInfoCommand.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
                        //aInfoCommand.Connection = FClientData.Owner.GlobalConnection;
                        IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
                        if (FSYS_REFVAL != null)
                            FSYS_REFVAL.Dispose();
                        FSYS_REFVAL = new DataSet();
                        aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL where REFVAL_NO = '{0}'", fielditem.RefValNo);
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, FSYS_REFVAL, fielditem.RefValNo);

                        WebRefVal aWebRefVal = new WebRefVal();
                        aWebRefVal.ID = wqc.WebRefVal;
                        aWebRefVal.DataTextField = FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString();
                        aWebRefVal.DataValueField = FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString();
                        aWebRefVal.DataSourceID = String.Format("wds{0}{1}", BlockItem.ProviderName, wqc.Column);
                        aWebRefVal.Visible = false;
                        InsertControl(Page, aWebRefVal);
                        break;
                    }
                }
            }

            WebDevPage.IHTMLElement Navigator = (WebDevPage.IHTMLElement)FDesignerDocument.webControls.item("WebNavigator1", 0);
            if (Navigator != null)
            {
                SetCollectionValue(Navigator, typeof(WebNavigator).GetProperty("QueryFields"), QueryFields);
            }
            WebDevPage.IHTMLElement ClientQuery = (WebDevPage.IHTMLElement)FDesignerDocument.webControls.item("WebClientQuery1", 0);
            if (ClientQuery != null)
            {
                SetCollectionValue(ClientQuery, typeof(WebClientQuery).GetProperty("Columns"), QueryColumns);
            }
            //刷不了Schema所以直接用写的

            WebDevPage.IHTMLElement FormView = (WebDevPage.IHTMLElement)FDesignerDocument.webControls.item(BlockItem.ContainerName, 0);
            if (FormView != null)
            {
                RefreshFormView(FormView, BlockItem);
            }
#else
            WebFormView wfvMaster = (WebFormView)FPage.FindControl(BlockItem.ContainerName) as WebFormView;
            WebDataSource aDataSource = FindWebDataSource(BlockItem);
            WebDefault aDefault = new WebDefault();
            wfvMaster.DataSourceID = aDataSource.ID;
            aDefault.ID = "wd" + BlockItem.ProviderName;
            aDefault.DataSourceID = aDataSource.ID;
            aDefault.DataMember = aDataSource.DataMember;
            WebValidate aValidate = new WebValidate();
            aValidate.ID = "wv" + BlockItem.ProviderName;
            aValidate.DataSourceID = aDataSource.ID;
            aValidate.DataMember = aDataSource.DataMember;
            Boolean Done = false;

            //Generate RESX
            GenResx(BlockItem);

            //wfvMaster.EditItemTemplate = new MyTemplate("WebFormViewEditItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FClientData.Owner.GlobalConnection, FWebRefValList);
            FormViewDesigner aDesigner = FDesignerHost.GetDesigner(wfvMaster) as FormViewDesigner;

            //DataSet Dset = new DataSet();
            if (FPage.Site.DesignMode)
            {
                //Dset = GetDD(wfvMaster);
            }

            foreach (TemplateGroup tempGroup in aDesigner.TemplateGroups)
            {
                foreach (TemplateDefinition tempDefin in tempGroup.Templates)
                {
                    if (tempDefin.Name == "EditItemTemplate" || tempDefin.Name == "InsertItemTemplate" || tempDefin.Name == "ItemTemplate")
                    {
                        StringBuilder builder = new StringBuilder();
                        string content = tempDefin.Content;
                        if (content == null || content.Length == 0)
                            continue;

                        string[] ctrlTexts = content.Split("\r\n".ToCharArray());
                        //Control[] ctrls = ControlParser.ParseControls(host, content);
                        int i = 0;
                        int j = 0;
                        int m = wfvMaster.LayOutColNum * 2;

                        List<string> lists = new List<string>();
                        String ExtraName = "";

                        foreach (TBlockFieldItem aFieldItem in BlockItem.BlockFieldItems)
                        {
                            if (!Done)
                            {
                                GenDefault(aFieldItem, aDefault, aValidate);
                                CreateQueryField(aFieldItem, "", null, BlockItem.ProviderName);
                            }

                            lists.Add(aFieldItem.DataField);
                            if ((aFieldItem.RefValNo != null && aFieldItem.RefValNo != "") || aFieldItem.RefField != null)
                            {
                                //<InfoLight:WebRefVal ID="WebRefVal2" runat="server" BindingValue='<%# Bind("GROUPNAME") %>'
                                //   ButtonImageUrl="../Image/refval/RefVal.gif" DataBindingField="GROUPNAME" DataSourceID="WebDataSource1"
                                //   DataTextField="GROUPNAME" DataValueField="GROUPID" ReadOnly="False" ResxDataSet=""
                                //   ResxFilePath="" UseButtonImage="True">
                                //   </InfoLight:WebRefVal>
                                String DataSourceID = GenWebDataSource(aFieldItem, BlockItem.ProviderName, "RefVal", "").ID;
                                switch (tempDefin.Name)
                                {
                                    case "EditItemTemplate":
                                        ExtraName = "E";
                                        break;
                                    case "InsertItemTemplate":
                                        ExtraName = "I";
                                        if (aFieldItem.DefaultValue != null && aFieldItem.DefaultValue != "")
                                        {
                                            FormViewField aViewField = new FormViewField();
                                            aViewField.ControlID = "wrv" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName;
                                            aViewField.FieldName = aFieldItem.DataField;
                                            wfvMaster.Fields.Add(aViewField);
                                        }
                                        break;
                                    case "ItemTemplate":
                                        ExtraName = "";
                                        break;
                                }
                                if (tempDefin.Name == "ItemTemplate")
                                {
                                    String FormatStyle = aFieldItem.EditMask;
                                    String S6 = String.Format("<InfoLight:WebRefVal ID=\"{0}\" runat=\"server\" BindingValue='<%# Bind(\"{1}\"{5}) %>' " +
                                        "ButtonImageUrl=\"../Image/refval/RefVal.gif\" DataBindingField=\"{1}\" DataSourceID=\"{2}\" " +
                                        "DataTextField=\"{3}\" DataValueField=\"{4}\" ReadOnly=\"True\" ResxDataSet=\"\" " +
                                        "ResxFilePath=\"\" UseButtonImage=\"True\" Width=\"130px\" BackColor=\"Transparent\" BorderStyle=\"None\"> " +
                                        "</InfoLight:WebRefVal>",
                                        "wrv" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                        aFieldItem.DataField,
                                        DataSourceID,
                                        FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString(),
                                        FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString(),
                                        FormatStyle
                                        );
                                    lists.Add(S6);
                                }
                                else
                                {
                                    String FormatStyle = aFieldItem.EditMask;
                                    String S1 = String.Format("<InfoLight:WebRefVal ID=\"{0}\" runat=\"server\" BindingValue='<%# Bind(\"{1}\"{5}) %>' " +
                                        "ButtonImageUrl=\"../Image/refval/RefVal.gif\" DataBindingField=\"{1}\" DataSourceID=\"{2}\" " +
                                        "DataTextField=\"{3}\" DataValueField=\"{4}\" ReadOnly=\"False\" ResxDataSet=\"\" " +
                                        "ResxFilePath=\"\" UseButtonImage=\"True\"> " +
                                        "</InfoLight:WebRefVal>",
                                        "wrv" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                        aFieldItem.DataField,
                                        DataSourceID,
                                        FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString(),
                                        FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString(),
                                        FormatStyle
                                        );
                                    lists.Add(S1);
                                }
                            }
                            else if (aFieldItem.ControlType == "ComboBox")
                            {
                                String FormatStyle = aFieldItem.EditMask;
                                String DataSourceID = GenWebDataSource(aFieldItem, aFieldItem.ComboTableName, "ComboBox", "").ID;
                                String S5 = "";
                                switch (tempDefin.Name)
                                {
                                    case "EditItemTemplate":
                                        ExtraName = "E";
                                        S5 = String.Format("<InfoLight:WebDropDownList id=\"{0}\" runat=\"server\" DataMember=\"{1}\" DataSourceID=\"{2}\" __designer:wfdid=\"w3\" DataTextField=\"{3}\" Filter DataValueField=\"{4}\" AutoInsertEmptyData=\"False\" SelectedValue='<%# Bind(\"{5}\"{6} Width=\"130px\") %>'></InfoLight:WebDropDownList>",
                                            "wdd" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                            aFieldItem.ComboTableName,
                                            DataSourceID,
                                            aFieldItem.ComboTextField,
                                            aFieldItem.ComboValueField,
                                            aFieldItem.DataField,
                                            FormatStyle);
                                        break;
                                    case "InsertItemTemplate":
                                        ExtraName = "I";
                                        S5 = String.Format("<InfoLight:WebDropDownList id=\"{0}\" runat=\"server\" DataMember=\"{1}\" DataSourceID=\"{2}\" __designer:wfdid=\"w3\" DataTextField=\"{3}\" Filter DataValueField=\"{4}\" AutoInsertEmptyData=\"False\" SelectedValue='<%# Bind(\"{5}\"{6} Width=\"130px\") %>'></InfoLight:WebDropDownList>",
                                            "wdd" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                            aFieldItem.ComboTableName,
                                            DataSourceID,
                                            aFieldItem.ComboTextField,
                                            aFieldItem.ComboValueField,
                                            aFieldItem.DataField,
                                            FormatStyle);
                                        if (aFieldItem.DefaultValue != null && aFieldItem.DefaultValue != "")
                                        {
                                            FormViewField aViewField = new FormViewField();
                                            aViewField.ControlID = "wdd" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName;
                                            aViewField.FieldName = aFieldItem.DataField;
                                            wfvMaster.Fields.Add(aViewField);
                                        }
                                        break;
                                    case "ItemTemplate":
                                        ExtraName = "";
                                        S5 = String.Format("<asp:Label ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{2}) %>'></asp:Label>", "l" + aFieldItem.DataField, aFieldItem.DataField, FormatStyle);
                                        break;
                                }
                                lists.Add(S5);
                            }
                            else if (aFieldItem.ControlType == "ValidateBox")
                            {
                                String FormatStyle = aFieldItem.EditMask;
                                String S6 = "";
                                switch (tempDefin.Name)
                                {
                                    case "EditItemTemplate":
                                        ExtraName = "E";
                                        S6 = String.Format("<InfoLight:WebValidateBox ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{3}) %>' ValidateField=\"{1}\" WebValidateID=\"{2}\"></InfoLight:WebValidateBox></td>",
                                            "wvb" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                            aFieldItem.DataField,
                                            aValidate.ID,
                                            FormatStyle);
                                        break;
                                    case "InsertItemTemplate":
                                        ExtraName = "I";
                                        if (aFieldItem.DefaultValue != null && aFieldItem.DefaultValue != "")
                                        {
                                            FormViewField aViewField = new FormViewField();
                                            aViewField.ControlID = "wdd" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName;
                                            aViewField.FieldName = aFieldItem.DataField;
                                            wfvMaster.Fields.Add(aViewField);
                                        }
                                        S6 = String.Format("<InfoLight:WebValidateBox ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{3}) %>' ValidateField=\"{1}\" WebValidateID=\"{2}\"></InfoLight:WebValidateBox></td>",
                                            "wvb" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                            aFieldItem.DataField,
                                            aValidate.ID,
                                            FormatStyle);
                                        break;
                                    case "ItemTemplate":
                                        ExtraName = "";
                                        S6 = String.Format("<asp:Label ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{2}) %>'></asp:Label>", "l" + aFieldItem.DataField, aFieldItem.DataField, FormatStyle);
                                        break;
                                }
                                lists.Add(S6);
                            }
                            else if (aFieldItem.ControlType == "CheckBox")
                            {
                                String FormatStyle = aFieldItem.EditMask;
                                String S6 = "";
                                switch (tempDefin.Name)
                                {
                                    case "EditItemTemplate":
                                        ExtraName = "E";
                                        S6 = String.Format("<asp:CheckBox ID=\"{0}\" runat=\"server\" Checked='<%# Bind(\"{1}\"{2}) %>'></asp:CheckBox></td>",
                                            "cb" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                            aFieldItem.DataField,
                                            FormatStyle);
                                        break;
                                    case "InsertItemTemplate":
                                        ExtraName = "I";
                                        S6 = String.Format("<asp:CheckBox ID=\"{0}\" runat=\"server\" Checked='<%# Bind(\"{1}\"{2}) %>'></asp:CheckBox></td>",
                                            "wvb" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                            aFieldItem.DataField,
                                            FormatStyle);
                                        break;
                                    case "ItemTemplate":
                                        ExtraName = "";
                                        S6 = String.Format("<asp:Label ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{2}) %>'></asp:Label>", "l" + aFieldItem.DataField, aFieldItem.DataField, FormatStyle);
                                        break;
                                }
                                lists.Add(S6);
                            }
                            else
                            {
                                if (aFieldItem.DataType == typeof(DateTime) || (aFieldItem.ControlType != null && aFieldItem.ControlType.ToUpper() == "DATETIMEBOX"))
                                {
                                    String DataTimeType = aFieldItem.EditMask == "" ? "ShortDate" : aFieldItem.EditMask;
                                    String FormatStyle = "";
                                    if (DataTimeType == "ShortDate")
                                        FormatStyle = ",\"{0:d}\"";
                                    else
                                        FormatStyle = ",\"{0:D}\"";

                                    //                                  <InfoLight:WebDateTimePicker id="WebDateTimePicker1" runat="server" Width="100px" Text='<%# Bind("GROUPID") %>' __designer:wfdid="w14" UseButtonImage="True" DateFormat="None" DateTimeType="DateTime"></InfoLight:WebDateTimePicker>
                                    String S4 = "";
                                    switch (tempDefin.Name)
                                    {
                                        case "EditItemTemplate":
                                            ExtraName = "E";
                                            S4 = String.Format("<InfoLight:WebDateTimePicker id=\"{0}\" runat=\"server\" Width=\"100px\" Text='<%# Bind(\"{1}\"{2}) %>' __designer:wfdid=\"w14\" UseButtonImage=\"True\" DateFormat=\"" + DataTimeType + "\" DateTimeType=\"DateTime\"></InfoLight:WebDateTimePicker>",
                                                "wdtp" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                                aFieldItem.DataField,
                                                FormatStyle);
                                            break;
                                        case "InsertItemTemplate":
                                            ExtraName = "I";
                                            S4 = String.Format("<InfoLight:WebDateTimePicker id=\"{0}\" runat=\"server\" Width=\"100px\" Text='<%# Bind(\"{1}\"{2}) %>' __designer:wfdid=\"w14\" UseButtonImage=\"True\" DateFormat=\"" + DataTimeType + "\" DateTimeType=\"DateTime\"></InfoLight:WebDateTimePicker>",
                                                "wdtp" + BlockItem.ProviderName + aFieldItem.DataField + ExtraName,
                                                aFieldItem.DataField,
                                                FormatStyle);
                                            break;
                                        case "ItemTemplate":
                                            ExtraName = "";
                                            S4 = String.Format("<asp:Label ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{2}) %>'></asp:Label>", "l" + aFieldItem.DataField, aFieldItem.DataField, FormatStyle);
                                            break;
                                    }
                                    lists.Add(S4);
                                }
                                else
                                {
                                    String FormatStyle = aFieldItem.EditMask;

                                    if (tempDefin.Name == "ItemTemplate")
                                    {
                                        //<asp:Label ID="GROUPNAMELabel" runat="server" Text='<%# Bind("GROUPNAME") %>'></asp:Label>
                                        String S3 = String.Format("<asp:Label ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{2}) %>'></asp:Label>", "l" + aFieldItem.DataField, aFieldItem.DataField, FormatStyle);
                                        lists.Add(S3);
                                    }
                                    else
                                    {
                                        if (tempDefin.Name == "InsertItemTemplate")
                                        {
                                            if (aFieldItem.DefaultValue != null && aFieldItem.DefaultValue != "")
                                            {
                                                FormViewField aViewField = new FormViewField();
                                                aViewField.ControlID = "tb" + aFieldItem.DataField;
                                                aViewField.FieldName = aFieldItem.DataField;
                                                wfvMaster.Fields.Add(aViewField);
                                            }
                                        }
                                        //<asp:TextBox ID="DESCRIPTIONTextBox" runat="server" Text='<%# Bind("DESCRIPTION") %>'></asp:TextBox>
                                        String S4 = String.Format("<asp:TextBox ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{2}) %>'></asp:TextBox>", "tb" + aFieldItem.DataField, aFieldItem.DataField, FormatStyle);
                                        lists.Add(S4);
                                    }
                                }
                            }
                        }
                        Done = true;

                        j = j * 2;

                        if (m > 0)
                        {
                            builder.Append("<table>");
                        }

                        foreach (string ctrlText in lists.ToArray())
                        {
                            if (ctrlText == null || ctrlText.Length == 0)
                                continue;

                            if (m > 0)
                            {
                                if (i % m == 0)
                                {
                                    builder.Append("<tr>");
                                }

                                builder.Append("<td>");
                            }
                            // add dd

                            string ddText = "";
                            if (tempDefin.Name != "ItemTemplate")
                            {
                                //ddText = GetValidateText(ctrlText);
                                //ddText = GetDDText(ddText, BlockItem);
                                ddText = GetDDText(ctrlText, BlockItem, tempDefin.Name);
                            }
                            else
                            {
                                ddText = GetDDText(ctrlText, BlockItem, tempDefin.Name);
                            }
                            builder.Append(ddText);
                            builder.Append("\r\n");

                            if (m > 0)
                            {
                                builder.Append("</td>");

                                if (i % m == m - 1)
                                {
                                    builder.Append("</tr>");
                                }
                            }
                            i++;
                        }

                        if (m > 0)
                        {
                            if (i % m != 0)
                            {
                                int n = m - (i % m);
                                int q = 0;
                                while (q < n)
                                {
                                    builder.Append("<td></td>");
                                    q++;
                                }
                                builder.Append("</tr>");
                            }
                            builder.Append("</table>");
                        }

                        tempDefin.Content = builder.ToString();
                    }
                }
            }

            FWebDefaultList.Add(aDefault);
            FWebValidateList.Add(aValidate);
            IComponentChangeService FComponentChangeService = (IComponentChangeService)FDesignerHost.RootComponent.Site.GetService(typeof(IComponentChangeService));
            FComponentChangeService.OnComponentChanged(wfvMaster, null, "", "M");
#endif
        }

#if VS90
        /// <summary>
        /// 刷新formview的内容
        /// </summary>
        /// <param name="formViewElement">formview的结构</param>
        /// <param name="blockItem">blockItem</param>
        private void RefreshFormView(WebDevPage.IHTMLElement formViewElement, TBlockItem blockItem)
        {
            if (formViewElement != null)
            {
                StringBuilder builderEditTemplate = new StringBuilder("<EditItemTemplate>\r\n\t<table class=\"container_table\">");
                StringBuilder builderInsertTemplate = new StringBuilder("<InsertItemTemplate>\r\n\t<table class=\"container_table\">");
                StringBuilder builderItemTemplate = new StringBuilder("<ItemTemplate>\r\n\t<table class=\"container_table\">");
                FormViewFieldsCollection fields = new FormViewFieldsCollection(null, typeof(FormViewField));
                int layoutcolnum = int.Parse(formViewElement.getAttribute("LayOutColNum", 0).ToString());
                for (int i = 0; i < blockItem.BlockFieldItems.Count; i++)
                {
                    TBlockFieldItem item = (TBlockFieldItem)blockItem.BlockFieldItems[i];
                    string controlid = string.Empty;
                    if (i % layoutcolnum == 0 || layoutcolnum == 1)
                    {
                        builderEditTemplate.AppendLine("\t\t<tr>");
                        builderInsertTemplate.AppendLine("\t\t<tr>");
                        builderItemTemplate.AppendLine("\t\t<tr>");
                    }
                    builderEditTemplate.AppendLine("\t\t\t<td>");
                    builderEditTemplate.AppendLine(string.Format("\t\t\t\t{0}", GetCaptionLabelXml(item, true)));
                    builderEditTemplate.AppendLine("\t\t\t</td>");
                    builderEditTemplate.AppendLine("\t\t\t<td>");
                    controlid = "E";
                    builderEditTemplate.AppendLine(string.Format("\t\t\t\t{0}", GetControlXml(item, blockItem.ProviderName, ref controlid)));
                    builderEditTemplate.AppendLine("\t\t\t</td>");

                    builderInsertTemplate.AppendLine("\t\t\t<td>");
                    builderInsertTemplate.AppendLine(string.Format("\t\t\t\t{0}", GetCaptionLabelXml(item, true)));
                    builderInsertTemplate.AppendLine("\t\t\t</td>");
                    builderInsertTemplate.AppendLine("\t\t\t<td>");
                    controlid = "I";
                    builderInsertTemplate.AppendLine(string.Format("\t\t\t\t{0}", GetControlXml(item, blockItem.ProviderName, ref controlid)));
                    builderInsertTemplate.AppendLine("\t\t\t</td>");

                    builderItemTemplate.AppendLine("\t\t\t<td>");
                    builderItemTemplate.AppendLine(string.Format("\t\t\t\t{0}", GetCaptionLabelXml(item, false)));
                    builderItemTemplate.AppendLine("\t\t\t</td>");

                    builderItemTemplate.AppendLine("\t\t\t<td>");
                    builderItemTemplate.AppendLine(string.Format("\t\t\t\t{0}", GetLabelXml(item, blockItem.ProviderName, ref controlid)));
                    builderItemTemplate.AppendLine("\t\t\t</td>");
                    if (i % layoutcolnum == layoutcolnum - 1 || layoutcolnum == 1 || i == blockItem.BlockFieldItems.Count - 1)
                    {
                        builderEditTemplate.AppendLine("\t\t</tr>");
                        builderInsertTemplate.AppendLine("\t\t</tr>");
                        builderItemTemplate.AppendLine("\t\t</tr>");
                    }

                    FormViewField field = new FormViewField();
                    field.FieldName = item.DataField;
                    field.ControlID = controlid;
                    fields.Add(field);
                }
                builderEditTemplate.AppendLine("\t</table>\r\n</EditItemTemplate>");
                builderInsertTemplate.AppendLine("\t</table>\r\n</InsertItemTemplate>");
                builderItemTemplate.AppendLine("\t</table>\r\n</ItemTemplate>");

                SetCollectionValue(formViewElement, typeof(WebFormView).GetProperty("Fields"), fields);
                SetTemplateValue(formViewElement, builderItemTemplate.ToString(), "ItemTemplate");
                SetTemplateValue(formViewElement, builderInsertTemplate.ToString(), "InsertItemTemplate");
                SetTemplateValue(formViewElement, builderEditTemplate.ToString(), "EditItemTemplate");
            }
        }
#endif

        /// <summary>
        /// 取得Control对应的xml
        /// </summary>
        /// <param name="item">blockfielditem</param>
        /// <param name="tableName">tablename</param>
        /// <param name="id">控件的id</param>
        /// <returns>xml</returns>
        private string GetControlXml(TBlockFieldItem item, string tableName, ref string id)
        {
            WebControl control = null;
            PropertyInfo info = null;

            #region DropDownList
            if (string.Compare(item.ControlType, "combobox", true) == 0)
            {
                control = new WebDropDownList();
                control.ID = string.Format("{0}DropDownList", item.DataField);
                control.Width = new Unit(130, UnitType.Pixel);
                (control as WebDropDownList).DataSourceID = GenWebDataSource(item, tableName, "ComboBox", string.Empty).ID;
                (control as WebDropDownList).DataMember = item.ComboTableName;
                (control as WebDropDownList).DataTextField = item.ComboTextField;
                (control as WebDropDownList).DataValueField = item.ComboValueField;
                info = control.GetType().GetProperty("SelectedValue");
            }
            #endregion

            #region RefVal
            else if (string.Compare(item.ControlType, "refvalbox", true) == 0)
            {
#warning GenWebDataSource未完成FSYS_REFVAL部分
                control = new WebRefVal();
                control.ID = string.Format("{0}RefVal", item.DataField);
                if (!string.IsNullOrEmpty(item.RefValNo) || (item.RefField != null))
                {
                    (control as WebRefVal).DataSourceID = GenWebDataSource(item, tableName, "RefVal", string.Empty).ID;
                    (control as WebRefVal).DataBindingField = item.DataField;
                    (control as WebRefVal).DataTextField = FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString();
                    (control as WebRefVal).DataValueField = FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString();
                    if (!string.IsNullOrEmpty(item.RefValNo))
                    {
                        IDbConnection conn = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, false);
                        InfoCommand command = new InfoCommand(FClientData.DatabaseType);
                        command.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
                        //command.Connection = conn;
                        command.CommandText = String.Format("Select * from SYS_REFVAL_D1 where REFVAL_NO = '{0}'", item.RefValNo);
                        IDbDataAdapter adapter = WzdUtils.AllocateDataAdapter(FClientData.DatabaseType);
                        adapter.SelectCommand = command.GetInternalCommand();
                        DataSet dataset = new DataSet();
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, adapter, dataset, item.RefValNo);
                        if (dataset != null && dataset.Tables.Count > 0 && dataset.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow DR in dataset.Tables[0].Rows)
                            {
                                WebRefColumn refcolumn = new WebRefColumn();
                                refcolumn.ColumnName = DR["FIELD_NAME"].ToString();
                                refcolumn.HeadText = DR["HEADER_TEXT"].ToString();
                                refcolumn.Width = 100;
                                (control as WebRefVal).Columns.Add(refcolumn);
                            }
                        }
                    }
                    info = control.GetType().GetProperty("BindingValue");
                }
                else
                {
                    control = new System.Web.UI.WebControls.TextBox();
                    control.ID = string.Format("{0}TextBox", item.DataField);
                    info = control.GetType().GetProperty("Text");
                }

            }
            #endregion

            #region DateTimePicker
            else if (string.Compare(item.ControlType, "datetimebox", true) == 0)
            {
                control = new WebDateTimePicker();
                control.ID = string.Format("{0}DateTimePicker", item.DataField);
                if (string.IsNullOrEmpty(item.EditMask))
                {
                    (control as WebDateTimePicker).DateFormat = dateFormat.ShortDate;
                }
                if (item.DataType == typeof(DateTime))
                {
                    info = control.GetType().GetProperty("Text");
                }
                else if (item.DataType == typeof(string))
                {
                    (control as WebDateTimePicker).DateTimeType = dateTimeType.VarChar;
                    info = control.GetType().GetProperty("DataString");
                }
            }
            #endregion

            #region ValidateBox
            else if (string.Compare(item.ControlType, "validatebox", true) == 0)
            {
                control = new WebValidateBox();
                control.ID = string.Format("{0}ValidateBox", item.DataField);
                (control as WebValidateBox).WebValidateID = string.Format("wv{0}", tableName);
                (control as WebValidateBox).ValidateField = item.DataField;
                info = control.GetType().GetProperty("Text");
            }
            #endregion

            #region CheckBox
            else if (string.Compare(item.ControlType, "checkbox", true) == 0)
            {
                control = new System.Web.UI.WebControls.CheckBox();
                control.ID = string.Format("{0}CheckBox", item.DataField);
                info = control.GetType().GetProperty("Checked");
            }
            #endregion

            #region TextBox
            else
            {
                control = new System.Web.UI.WebControls.TextBox();
                control.ID = string.Format("{0}TextBox", item.DataField);
                info = control.GetType().GetProperty("Text");
            }
            #endregion

            control.ID = string.Format("{0}{1}", control.ID, id);
            id = control.ID;
            item.EditMask = FormatEditMask(item.EditMask);
            return GetControlXml(control, info, item.DataField, item.EditMask);
        }

        /// <summary>
        /// 取得CaptionLabel对应的xml
        /// </summary>
        /// <param name="item"><blockfielditem/param>
        /// <returns>xml</returns>
        private string GetCaptionLabelXml(TBlockFieldItem item, bool b)
        {
            System.Web.UI.WebControls.Label label = new System.Web.UI.WebControls.Label();
            label.Text = string.IsNullOrEmpty(item.Description) ? item.DataField : item.Description;
            if (b)
            {
                label.ID = string.Format("Caption{0}", item.DataField);
            }
            else
            {
                label.ID = string.Format("Caption{0}Label", item.DataField);
            }
            return GetControlXml(label);
        }

        /// <summary>
        /// 取得label对应的xml
        /// </summary>
        /// <param name="item">blockfielditem</param>
        /// <returns>xml</returns>
        private string GetLabelXml(TBlockFieldItem item, String tableName, ref String id)
        {
            String strLabel = String.Empty;
            if (string.Compare(item.ControlType, "refvalbox", true) == 0)
            {
                WebControl control = null;
                PropertyInfo info = null;
                if (!string.IsNullOrEmpty(item.RefValNo) || (item.RefField != null))
                {
                    control = new WebRefVal();
                    control.ID = string.Format("{0}RefVal", item.DataField);
                    (control as WebRefVal).DataSourceID = GenWebDataSource(item, tableName, "RefVal", string.Empty).ID;
                    (control as WebRefVal).DataBindingField = item.DataField;
                    (control as WebRefVal).DataTextField = FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString();
                    (control as WebRefVal).DataValueField = FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString();
                    (control as WebRefVal).BackColor = System.Drawing.Color.Transparent;
                    (control as WebRefVal).BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
                    (control as WebRefVal).ReadOnly = true;
                    (control as WebRefVal).Width = 100;
                    info = control.GetType().GetProperty("BindingValue");
                    id = control.ID;
                    strLabel = GetControlXml(control, info, item.DataField, item.EditMask);
                }
                else
                {
                    control = new System.Web.UI.WebControls.Label();
                    control.ID = string.Format("{0}Label", item.DataField);
                    strLabel = GetControlXml(control, control.GetType().GetProperty("Text"), item.DataField, item.EditMask);
                }
                //control.ID = string.Format("{0}{1}", control.ID, id);

                int i = strLabel.IndexOf("runat=\"server\"");
                strLabel = strLabel.Insert(i + 14, " Width=\"100\" BackColor=\"Transparent\"");
            }
            else
            {
                //用上面的方法实现
                System.Web.UI.WebControls.Label label = new System.Web.UI.WebControls.Label();
                label.ID = string.Format("{0}Label", item.DataField);
                strLabel = GetControlXml(label, label.GetType().GetProperty("Text"), item.DataField, item.EditMask);
            }
            return strLabel;
        }

        /// <summary>
        /// 取得Collecion对应的xml
        /// </summary>
        /// <param name="prop">Collection的propinfo</param>
        /// <param name="collection">Collection的value</param>
        /// <returns>xml</returns>
        private string GetCollectionXml(PropertyInfo prop, InfoOwnerCollection collection)
        {
            StringBuilder builder = new StringBuilder();
            if (prop != null && collection != null && prop.PropertyType == collection.GetType())
            {
                if (collection.Count > 0)
                {
                    builder.AppendLine(string.Format("\t<{0}>", prop.Name));
                    for (int i = 0; i < collection.Count; i++)
                    {
                        builder.Append(string.Format("\t\t<{0}:{1} ", INFOLIGHTMARK, collection.ItemType.Name));
                        PropertyInfo[] infos = collection.ItemType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
                        for (int j = 0; j < infos.Length; j++)
                        {
                            if (!IsVisibilityHidden(infos[j]))
                            {
                                if (infos[j].PropertyType == typeof(string) || infos[j].PropertyType == typeof(int) || infos[j].PropertyType == typeof(bool)
                                    || infos[j].PropertyType.BaseType == typeof(Enum))
                                {
                                    if (!infos[j].Name.Equals("Name"))
                                    {
                                        object value = infos[j].GetValue(collection[i], null);
                                        object defaultvalue = GetDefaultValue(infos[j]);
                                        if (infos[j].CanWrite && value != defaultvalue)
                                        {
                                            builder.Append(string.Format("{0}=\"{1}\" ", infos[j].Name, value));
                                        }
                                    }
                                }
                            }
                        }
                        builder.AppendLine("/>");
                    }
                    builder.AppendLine(string.Format("\t</{0}>", prop.Name));
                }
            }
            return builder.ToString();
        }

        private void SetBlockFieldDataComponent(TBlockItem BlockItem, string DataSetName)
        {
            InfoBindingSource aBindingSource = FDesignerHost.CreateComponent(typeof(InfoBindingSource), "ibs" + BlockItem.ProviderName) as InfoBindingSource;
            if (BlockItem.ParentItemName == "")
            {
                aBindingSource.DataSource = FDataSet;
                aBindingSource.DataMember = BlockItem.ProviderName;
            }
            else
            {   
                TBlockItem ParentItem = ((TBlockItems)BlockItem.Collection).FindItem(BlockItem.ParentItemName);
                aBindingSource.DataSource = ParentItem.BindingSource;
                aBindingSource.DataMember = BlockItem.RelationName;
            }
            BlockItem.BindingSource = aBindingSource;
        }

		private void GenWebBlock()
		{
            foreach (TBlockItem BlockItem in FClientData.Blocks)
            {
                if (BlockItem.WebContainerControl != null && BlockItem.ProviderName != null && BlockItem.ProviderName != "")
                {
                    if (BlockItem.WebContainerControl is WebGridView)
                    {
                        GenWebGridViewBlock(BlockItem);
                    }
                    if (BlockItem.WebContainerControl is WebFormView)
                    {
                        GenWebFormViewBlock(BlockItem);
                    }
                    if (BlockItem.WebContainerControl is WebDetailsView)
                    {
                        GenWebDetailsViewBlock(BlockItem);
                    }
                }
            }
        }

        private void GenDataSet()
        {
            //WebDataSet
            string Path = FPI.get_FileNames(0);
            string FileName = System.IO.Path.GetFileNameWithoutExtension(Path) + ".aspx." + FClientData.Language;
            Path = System.IO.Path.GetDirectoryName(Path);
            FileName = Path + "\\" + FileName;
            if (!File.Exists(FileName))
            {
                MessageBox.Show(String.Format("File does not exists: {0}", FileName));
                return;
            }
            String Context = "";
            System.IO.StreamReader SR = new System.IO.StreamReader(FileName);
            Context = SR.ReadToEnd();
            SR.Close();
            foreach (InfoDataSet aDataSet in FClientData.DataSetList)
            {
                if (FClientData.Language == "cs")
                {
                    Context = Context.Replace(String.Format("this.{0}.RemoteName = null;", aDataSet.Site.Name), 
                        String.Format("this.{0}.RemoteName = \"{1}\";", aDataSet.Site.Name, aDataSet.RemoteName));
                    Context = Context.Replace(String.Format("this.{0}.RemoteName = \"\";", aDataSet.Site.Name),
                        String.Format("this.{0}.RemoteName = \"{1}\";", aDataSet.Site.Name, aDataSet.RemoteName));
                    Context = Context.Replace(String.Format("this.{0}.Active = false;", aDataSet.Site.Name), 
                        String.Format("this.{0}.Active = true;", aDataSet.Site.Name));
                }
                else if (FClientData.Language == "vb")
                {
                    Context = Context.Replace(String.Format("Me.{0}.RemoteName = Nothing", aDataSet.Site.Name), 
                        String.Format("Me.{0}.RemoteName = \"{1}\"", aDataSet.Site.Name, aDataSet.RemoteName));
                    Context = Context.Replace(String.Format("Me.{0}.Active = False", aDataSet.Site.Name), 
                        String.Format("Me.{0}.Active = True", aDataSet.Site.Name));
                }
            }
            System.IO.FileStream Filefs = new System.IO.FileStream(FileName, System.IO.FileMode.Create, 
                System.IO.FileAccess.ReadWrite);
            System.IO.StreamWriter SW = new System.IO.StreamWriter(Filefs);
            SW.Write(Context);
            SW.Close();
            Filefs.Close();
        }

        public void SaveWebDataSet(InfoDataSet ds)
        {
            string Path = FPI.get_FileNames(0);
            string FileName = Path + ".vi-VN.resx";

            string keyName = "WebDataSets";

            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(FileName);
            XmlNode aNode = xDoc.DocumentElement.FirstChild;
            while (aNode != null)
            {
                if (aNode.InnerText.Contains(keyName))
                {
                    FWizardDataSet.RemoteName = ds.RemoteName;

                    int x, y;
                    String temp;
                    x = aNode.InnerText.IndexOf("<Active>");
                    y = aNode.InnerText.IndexOf("</Active>");
                    temp = aNode.InnerText.Substring(x, (y - x) + 9);
                    aNode.InnerText = aNode.InnerText.Replace(temp, "<Active>" + FWizardDataSet.Active + "</Active>");

                    x = aNode.InnerText.IndexOf("<PacketRecords>");
                    y = aNode.InnerText.IndexOf("</PacketRecords>");
                    temp = aNode.InnerText.Substring(x, (y - x) + 16);
                    aNode.InnerText = aNode.InnerText.Replace(temp, "<PacketRecords>" + FWizardDataSet.PacketRecords + "</PacketRecords>");

                    x = aNode.InnerText.IndexOf("<RemoteName>");
                    y = aNode.InnerText.IndexOf("</RemoteName>");
                    temp = aNode.InnerText.Substring(x, (y - x) + 13);
                    aNode.InnerText = aNode.InnerText.Replace(temp, "<RemoteName>" + FWizardDataSet.RemoteName + "</RemoteName>");

                    x = aNode.InnerText.IndexOf("<ServerModify>");
                    y = aNode.InnerText.IndexOf("</ServerModify>");
                    temp = aNode.InnerText.Substring(x, (y - x) + 15);
                    aNode.InnerText = aNode.InnerText.Replace(temp, "<ServerModify>" + FWizardDataSet.ServerModify + "</ServerModify>");
                    break;
                }
                aNode = aNode.NextSibling;
            }
            xDoc.Save(FileName);
        }

        private void SetupWebDataSource()
        {
            foreach (InfoBindingSource aDataSource in FClientData.DataSourceList)
            {
#if VS90
                object oMaster = FDesignerDocument.webControls.item(aDataSource.Site.Name, 0);
                if (oMaster != null && oMaster is WebDevPage.IHTMLElement)
                {
                    ((WebDevPage.IHTMLElement)oMaster).setAttribute("DataMember", aDataSource.DataMember, 0);
                }
#else
                WebDataSource aWebDataSource = FPage.FindControl(aDataSource.Site.Name) as WebDataSource;
                aWebDataSource.DataMember = aDataSource.DataMember;
                IComponentChangeService FComponentChangeService = (IComponentChangeService)FDesignerHost.RootComponent.Site.GetService(typeof(IComponentChangeService));
                FComponentChangeService.OnComponentChanged(aWebDataSource, null, "", "M");
#endif
            }

            foreach (InfoDataSet aDataSet in FClientData.DataSetList)
            {
                //GetSchema
                if (FWizardDataSet != null)
                    FWizardDataSet.Dispose();
                FWizardDataSet = new InfoDataSet(true);
                FWizardDataSet.RemoteName = aDataSet.RemoteName;
                FWizardDataSet.Active = true;
                FWizardDataSet.ServerModify = false;
                FWizardDataSet.PacketRecords = 100;
                FWizardDataSet.AlwaysClose = false;

                SaveWebDataSet(FWizardDataSet);
            }
        }

        ArrayList allDefaults = new ArrayList();
        ArrayList allValidates = new ArrayList();
        private void GenWebGridViewBlock(TBlockItem BlockItem)
        {
#if VS90
            this.FClientData.TableName = BlockItem.TableName;
            InfoBindingSource aDataSource = FClientData.FindDataSource(BlockItem.BindingSource.Site.Name);
            object oMaster = FDesignerDocument.webControls.item(aDataSource.Site.Name, 0);

            WebDevPage.IHTMLElement eMaster = null;
            WebDevPage.IHTMLElement eWebGridView1 = null;

            if (oMaster == null || !(oMaster is WebDevPage.IHTMLElement))
                return;
            eMaster = (WebDevPage.IHTMLElement)oMaster;

            WebDefault Default = null;
            if (!allDefaults.Contains("wd" + BlockItem.ProviderName))
            {
                Default = new WebDefault();
                Default.ID = "wd" + BlockItem.ProviderName;
                Default.DataSourceID = eMaster.getAttribute("ID", 0).ToString();
                Default.DataMember = aDataSource.DataMember;

                allDefaults.Add(Default.ID);
            }

            WebValidate Validate = null;
            if (!allValidates.Contains("wv" + BlockItem.ProviderName))
            {
                Validate = new WebValidate();
                Validate.ID = "wv" + BlockItem.ProviderName;
                Validate.DataSourceID = eMaster.getAttribute("ID", 0).ToString();
                Validate.DataMember = aDataSource.DataMember;

                allValidates.Add(Validate.ID);
            }

            WebQueryFiledsCollection QueryFields = new WebQueryFiledsCollection(null, typeof(QueryField));
            WebQueryColumnsCollection QueryColumns = new WebQueryColumnsCollection(null, typeof(QueryColumns));
            foreach (TBlockFieldItem fielditem in BlockItem.BlockFieldItems)
            {
                GenDefault(fielditem, Default, Validate);
                GenQuery(fielditem, QueryFields, QueryColumns, BlockItem.ProviderName);
            }

            WebDevPage.IHTMLElement Page = FDesignerDocument.pageContentElement;
            if (Default != null)
                InsertControl(Page, Default);
            if (Validate != null)
                InsertControl(Page, Validate);

            foreach (TBlockFieldItem fielditem in BlockItem.BlockFieldItems)
            {
                foreach (WebQueryColumns wqc in QueryColumns)
                {
                    if (wqc.ColumnType == "ClientQueryRefValColumn" && wqc.Column == fielditem.DataField && fielditem.RefValNo != String.Empty)
                    {
                        WebDataSource aWebDataSource = new WebDataSource();
                        InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
                        aInfoCommand.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
                        //aInfoCommand.Connection = FClientData.Owner.GlobalConnection;
                        IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
                        if (FSYS_REFVAL != null)
                            FSYS_REFVAL.Dispose();
                        FSYS_REFVAL = new DataSet();
                        aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL where REFVAL_NO = '{0}'", fielditem.RefValNo);
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, FSYS_REFVAL, fielditem.RefValNo);

                        WebRefVal aWebRefVal = new WebRefVal();
                        aWebRefVal.ID = wqc.WebRefVal;
                        aWebRefVal.DataTextField = FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString();
                        aWebRefVal.DataValueField = FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString();
                        aWebRefVal.DataSourceID = String.Format("wds{0}{1}", BlockItem.ProviderName, wqc.Column);
                        aWebRefVal.Visible = false;
                        InsertControl(Page, aWebRefVal);
                        break;
                    }
                }
            }

            WebDevPage.IHTMLElement Navigator = (WebDevPage.IHTMLElement)FDesignerDocument.webControls.item("WebNavigator1", 0);
            if (Navigator != null)
            {
                SetCollectionValue(Navigator, typeof(WebNavigator).GetProperty("QueryFields"), QueryFields);
            }
            WebDevPage.IHTMLElement ClientQuery = (WebDevPage.IHTMLElement)FDesignerDocument.webControls.item("WebClientQuery1", 0);
            if (ClientQuery != null)
            {
                SetCollectionValue(ClientQuery, typeof(WebClientQuery).GetProperty("Columns"), QueryColumns);
            }

            object oWebGridView1 = FDesignerDocument.webControls.item(BlockItem.ContainerName, 0);
            eWebGridView1 = (WebDevPage.IHTMLElement)oWebGridView1;
            //eWebGridView1.setAttribute("DataMember", aDataSource.DataMember, 0);

            //这里本来想再往下找Columns节点的,可是找不到,只能先这样写了
            StringBuilder sb = new StringBuilder(eWebGridView1.innerHTML);
            AddNewRowControlCollection controls = new AddNewRowControlCollection(null, typeof(AddNewRowControlItem));

            
            int idx = eWebGridView1.innerHTML.IndexOf("</Columns>");
            if (idx == -1)
            {
                idx = sb.ToString().IndexOf("<SelectedRowStyle");
                sb.Insert(idx, "<Columns>\r\n            </Columns>");
            }
            List<string> KeyFields = new List<string>();
            foreach (TBlockFieldItem BFI in BlockItem.BlockFieldItems)
            {
                string controlid = string.Empty;
                WebGridView.AddNewRowControlType type = WebGridView.AddNewRowControlType.TextBox;

                idx = sb.ToString().IndexOf("</Columns>");
                if (!string.IsNullOrEmpty(BFI.RefValNo) || BFI.RefField != null)
                {
                    sb.Insert(idx, GenTemplateFieldHTML(BFI.ControlType, BlockItem, BFI));
                    controlid = "wrv" + BlockItem.ProviderName + BFI.DataField + "F";
                    type = WebGridView.AddNewRowControlType.RefVal;
                }
                else if (BFI.ControlType == "ComboBox" || BFI.ControlType == "ValidateBox" || BFI.ControlType == "CheckBox")
                {
                    sb.Insert(idx, GenTemplateFieldHTML(BFI.ControlType, BlockItem, BFI));
                    controlid = "wdd" + BlockItem.ProviderName + BFI.DataField + "F";
                    type = WebGridView.AddNewRowControlType.DropDownList;
                }
                else if (BFI.ControlType == "ValidateBox")
                {
                    sb.Insert(idx, GenTemplateFieldHTML(BFI.ControlType, BlockItem, BFI));
                    controlid = "wvb" + BlockItem.ProviderName + BFI.DataField + "F";
                    type = WebGridView.AddNewRowControlType.TextBox;
                }
                else if (BFI.ControlType == "CheckBox")
                {
                    sb.Insert(idx, GenTemplateFieldHTML(BFI.ControlType, BlockItem, BFI));
                    controlid = "cb" + BlockItem.ProviderName + BFI.DataField + "F";
                    type = WebGridView.AddNewRowControlType.CheckBox;
                }
                else
                {
                    if (BFI.DataType == typeof(DateTime) || (BFI.ControlType != null && BFI.ControlType == "DateTimeBox"))
                    {
                        sb.Insert(idx, GenTemplateFieldHTML("DateTimeBox", BlockItem, BFI));
                        controlid = "wdt" + BlockItem.ProviderName + BFI.DataField + "F";
                        type = WebGridView.AddNewRowControlType.DateTimePicker;
                    }
                    else
                    {
                        sb.Insert(idx, "\r            <asp:BoundField DataField=\"" + BFI.DataField + "\" HeaderText=\"" + (string.IsNullOrEmpty(BFI.Description) ? BFI.DataField : BFI.Description) + "\" SortExpression=\"" + BFI.DataField + "\" />\r\n            ");
                    }
                }
                if (controlid.Length > 0)
                {
                    AddNewRowControlItem item = new AddNewRowControlItem();
                    item.FieldName = BFI.DataField;
                    item.ControlID = controlid;
                    item.ControlType = type;
                    controls.Add(item);
                }
            }
            eWebGridView1.innerHTML = sb.ToString();
            SetCollectionValue(eWebGridView1, typeof(WebGridView).GetProperty("AddNewRowControls"), controls);
#else
            WebDataSource Detail = FindWebDataSource(BlockItem);
            WebGridView aGridView = (WebGridView)FPage.FindControl(BlockItem.ContainerName);
            //aGridView.DataMember = BlockItem.ProviderName;
            aGridView.DataSourceID = Detail.ID;
            System.Web.UI.WebControls.BoundField aBoundField = null;
            System.Web.UI.WebControls.TemplateField aTemplateField = null;
            WebDefault aDefault = new WebDefault();
            aDefault.ID = "wd" + BlockItem.ProviderName;
            aDefault.DataSourceID = Detail.ID;
            aDefault.DataMember = Detail.DataMember;
            WebValidate aValidate = new WebValidate();
            aValidate.ID = "wv" + BlockItem.ProviderName;
            aValidate.DataSourceID = Detail.ID;
            aValidate.DataMember = Detail.DataMember;

            List<string> KeyFields = new List<string>();
            foreach (TBlockFieldItem BFI in BlockItem.BlockFieldItems)
            {
                if ((BFI.RefValNo != null && BFI.RefValNo != "") || BFI.RefField != null)
                {
                    String DataSourceID = GenWebDataSource(BFI, BlockItem.ProviderName, "RefVal", "").ID;
                    aTemplateField = new System.Web.UI.WebControls.TemplateField();
                    aTemplateField.HeaderText = BFI.Description;
                    aTemplateField.SortExpression = BFI.DataField;
                    if (aTemplateField.HeaderText == "")
                        aTemplateField.HeaderText = BFI.DataField;
                    aTemplateField.EditItemTemplate = new WebControlTemplate("WebGridViewRefValEditItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FClientData.Owner.GlobalConnection, FWebRefValList, FClientData.DatabaseType, aGridView);
                    aTemplateField.ItemTemplate = new WebControlTemplate("WebGridViewRefValItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FClientData.Owner.GlobalConnection, FWebRefValList, FClientData.DatabaseType, aGridView);
                    aTemplateField.FooterTemplate = new WebControlTemplate("WebGridViewRefValFooterItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FClientData.Owner.GlobalConnection, FWebRefValList, FClientData.DatabaseType, aGridView);
                    aGridView.Columns.Add(aTemplateField);
                }
                else if (BFI.ControlType == "ComboBox")
                {
                    String DataSourceID = GenWebDataSource(BFI, BFI.ComboTableName, "ComboBox", "").ID;
                    aTemplateField = new System.Web.UI.WebControls.TemplateField();
                    aTemplateField.HeaderText = BFI.Description;
                    aTemplateField.SortExpression = BFI.DataField;
                    if (aTemplateField.HeaderText == "")
                        aTemplateField.HeaderText = BFI.DataField;
                    aTemplateField.EditItemTemplate = new WebControlTemplate("WebGridViewComboBoxEditItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FMyWebDropDownList, FLabelList);
                    aTemplateField.ItemTemplate = new WebControlTemplate("WebGridViewComboBoxItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FMyWebDropDownList, FLabelList);
                    aTemplateField.FooterTemplate = new WebControlTemplate("WebGridViewComboBoxFooterItemTemplate", BFI, BlockItem.ProviderName, DataSourceID, FMyWebDropDownList, FLabelList);
                    aGridView.Columns.Add(aTemplateField);
                }
                else if (BFI.ControlType == "ValidateBox")
                {
                    aTemplateField = new System.Web.UI.WebControls.TemplateField();
                    aTemplateField.HeaderText = BFI.Description;
                    aTemplateField.SortExpression = BFI.DataField;
                    if (aTemplateField.HeaderText == "")
                        aTemplateField.HeaderText = BFI.DataField;
                    aTemplateField.EditItemTemplate = new WebControlTemplate("WebGridViewValidateBoxEditItemTemplate", BFI, BlockItem.ProviderName, aValidate, FWebValidateBoxList, FLabelList);
                    aTemplateField.ItemTemplate = new WebControlTemplate("WebGridViewValidateBoxItemTemplate", BFI, BlockItem.ProviderName, aValidate, FWebValidateBoxList, FLabelList);
                    aTemplateField.FooterTemplate = new WebControlTemplate("WebGridViewValidateBoxFooterItemTemplate", BFI, BlockItem.ProviderName, aValidate, FWebValidateBoxList, FLabelList);
                    aGridView.Columns.Add(aTemplateField);
                }
                else
                {
                    if (BFI.DataType == typeof(DateTime) || (BFI.ControlType != null && BFI.ControlType.ToUpper() == "DATETIMEBOX"))
                    {
                        aTemplateField = new System.Web.UI.WebControls.TemplateField();
                        aTemplateField.HeaderText = BFI.Description;
                        aTemplateField.SortExpression = BFI.DataField;
                        if (aTemplateField.HeaderText == "")
                            aTemplateField.HeaderText = BFI.DataField;
                        aTemplateField.EditItemTemplate = new WebControlTemplate("WebGridViewDateTimeEditItemTemplate", BFI, BlockItem.ProviderName, FWebDateTimePickerList, FLabelList);
                        aTemplateField.ItemTemplate = new WebControlTemplate("WebGridViewDateTimeItemTemplate", BFI, BlockItem.ProviderName, FWebDateTimePickerList, FLabelList);
                        aTemplateField.FooterTemplate = new WebControlTemplate("WebGridViewDateTimeFooterItemTemplate", BFI, BlockItem.ProviderName, FWebDateTimePickerList, FLabelList);
                        aGridView.Columns.Add(aTemplateField);
                    }
                    else
                    {
                        aBoundField = new System.Web.UI.WebControls.BoundField();
                        aBoundField.DataField = BFI.DataField;
                        aBoundField.SortExpression = BFI.DataField;
                        aBoundField.HeaderText = BFI.Description;
                        //Field.HeaderStyle.Width = BFI.Length * ColumnWidthPixel;
                        if (aBoundField.HeaderText == "")
                            aBoundField.HeaderText = BFI.DataField;
                        aGridView.Columns.Add(aBoundField);
                    }
                }
                if (BFI.IsKey)
                    KeyFields.Add(BFI.DataField);

                GenDefault(BFI, aDefault, aValidate);
            }

            FWebDefaultList.Add(aDefault);
            FWebValidateList.Add(aValidate);
            IComponentChangeService aComponentChangeService = (IComponentChangeService)FDesignerHost.RootComponent.Site.GetService(typeof(IComponentChangeService));
            aComponentChangeService.OnComponentChanged(aGridView, null, "", "M");
#endif
        }

        /// <summary>
        /// 加入查询
        /// </summary>
        /// <param name="fieldItem">blockfielditem</param>
        /// <param name="queryFields">Navigator的查询集合</param>
        /// <param name="queryColumns">ClientQuery的查询集合</param>
        /// <param name="tableName">tablename</param>
        private void GenQuery(TBlockFieldItem fieldItem, WebQueryFiledsCollection queryFields, WebQueryColumnsCollection queryColumns
            , string tableName)
        {
            if (string.Compare(fieldItem.QueryMode, "normal", true) == 0
                  || string.Compare(fieldItem.QueryMode, "range", true) == 0)
            {
                if (queryFields != null)
                {
                    WebQueryField field = new WebQueryField();
                    field.FieldName = fieldItem.DataField;
                    field.Caption = string.IsNullOrEmpty(fieldItem.Description) ? fieldItem.DataField : fieldItem.Description;

                    if (string.Compare(fieldItem.ControlType, "textbox", true) == 0)
                    {
                        field.Mode = "TextBox";
                    }
                    else if (string.Compare(fieldItem.ControlType, "combobox", true) == 0)
                    {
                        field.Mode = "ComboBox";
                        field.RefVal = string.Format("wrv{0}{1}QF", tableName, fieldItem.DataField);
                    }
                    else if (string.Compare(fieldItem.ControlType, "refvalbox", true) == 0)
                    {
                        if (fieldItem.RefValNo == String.Empty)
                            field.Mode = "TextBox";
                        else
                        {
                            field.Mode = "RefVal";
                            field.RefVal = string.Format("wrv{0}{1}QF", tableName, fieldItem.DataField);
                        }
                    }
                    else if (string.Compare(fieldItem.ControlType, "datetimebox", true) == 0)
                    {
                        field.Mode = "Calendar";
                    }
                    if (string.Compare(fieldItem.QueryMode, "normal", true) == 0)
                    {
                        field.Condition = (fieldItem.DataType == typeof(string)) ? "%" : "=";
                    }
                    else
                    {
                        WebQueryField fieldrev = new WebQueryField();
                        fieldrev.FieldName = field.FieldName;
                        fieldrev.Caption = field.Caption;
                        fieldrev.Mode = field.Mode;
                        fieldrev.RefVal = field.RefVal;
                        fieldrev.Condition = ">=";
                        queryFields.Add(fieldrev);
                        field.Condition = "<=";
                    }
                    queryFields.Add(field);
                }
                if (queryColumns != null)
                {
                    WebQueryColumns column = new WebQueryColumns();
                    column.Column = fieldItem.DataField;
                    column.Caption = string.IsNullOrEmpty(fieldItem.Description) ? fieldItem.DataField : fieldItem.Description;
                    if (string.Compare(fieldItem.ControlType, "textbox", true) == 0)
                    {
                        column.ColumnType = "ClientQueryTextBoxColumn";
                    }
                    else if (string.Compare(fieldItem.ControlType, "combobox", true) == 0)
                    {
                        column.ColumnType = "ClientQueryComboBoxColumn";
                        column.WebRefVal = string.Format("wrv{0}{1}QF", tableName, fieldItem.DataField);
                    }
                    else if (string.Compare(fieldItem.ControlType, "refvalbox", true) == 0)
                    {
                        if (fieldItem.RefValNo == String.Empty)
                            column.ColumnType = "ClientQueryTextBoxColumn";
                        else
                        {
                            column.ColumnType = "ClientQueryRefValColumn";
                            column.WebRefVal = string.Format("wrv{0}{1}QF", tableName, fieldItem.DataField);
                        }
                    }
                    else if (string.Compare(fieldItem.ControlType, "datetimebox", true) == 0)
                    {
                        column.ColumnType = "ClientQueryCalendarColumn";
                    }
                    if (string.Compare(fieldItem.QueryMode, "normal", true) == 0)
                    {
                        column.Operator = (fieldItem.DataType == typeof(string)) ? "%" : "=";
                    }
                    else
                    {
                        WebQueryColumns columnrev = new WebQueryColumns();
                        columnrev.Column = column.Column;
                        columnrev.Caption = column.Caption;
                        columnrev.ColumnType = column.ColumnType;
                        columnrev.WebRefVal = column.WebRefVal;
                        columnrev.Operator = ">=";
                        queryColumns.Add(columnrev);
                        column.Operator = "<=";
                    }
                    queryColumns.Add(column);
                }
            }
        }
        
#if VS90
        /// <summary>
        /// 设置Control的Collection属性
        /// </summary>
        /// <param name="controlElement">Control的Element</param>
        /// <param name="prop">Collection的propinfo</param>
        /// <param name="collection">Collection的value</param>
        private void SetCollectionValue(WebDevPage.IHTMLElement controlElement, PropertyInfo prop, InfoOwnerCollection collection)
        {
            if (controlElement != null)
            {
                string collectionxml = GetCollectionXml(prop, collection);
                if (collectionxml.Length > 0)
                {
                    string html = controlElement.innerHTML;
                    int index = IndexOfBeginTag(html, prop.Name);
                    int length;
                    if (index > 0)
                    {
                        int indexend = IndexOfEndTag(html, prop.Name, out length);
                        html = html.Remove(indexend - index - length);
                    }
                    else
                    {
                        index = 0;
                    }
                    controlElement.innerHTML = html.Insert(index, collectionxml);
                }
            }
        }
#endif

        /// <summary>
        /// "Infolight"字串
        /// </summary>
        const string INFOLIGHTMARK = "Infolight";

        private bool IsVisibilityHidden(PropertyInfo info)
        {
            object[] attributes = info.GetCustomAttributes(typeof(System.ComponentModel.DesignerSerializationVisibilityAttribute), true);
            if (attributes != null && attributes.Length > 0)
            {
                if (((System.ComponentModel.DesignerSerializationVisibilityAttribute)attributes[0]).Visibility
                    == System.ComponentModel.DesignerSerializationVisibility.Hidden)
                {
                    return true;
                }
            }
            return false;
        }

        private object GetDefaultValue(PropertyInfo info)
        {
            object[] attributes = info.GetCustomAttributes(typeof(System.ComponentModel.DefaultValueAttribute), true);
            if (attributes != null && attributes.Length > 0)
            {
                return ((System.ComponentModel.DefaultValueAttribute)attributes[0]).Value;
            }
            return null;
        }

#if VS90
        /// <summary>
        /// 设置FormView的Template
        /// </summary>
        /// <param name="viewElement">FormView的Element</param>
        /// <param name="templatexml">Template的名字</param>
        /// <param name="templatename">Template的内容</param>
        private void SetTemplateValue(WebDevPage.IHTMLElement viewElement, string templatexml, string templatename)
        {
            if (viewElement != null)
            {
                if (templatexml.Length > 0)
                {
                    string html = viewElement.innerHTML;
                    int index = IndexOfBeginTag(html, templatename);
                    int length;
                    if (index > 0)
                    {
                        int indexend = IndexOfEndTag(html, templatename, out length);
                        html = html.Remove(indexend - index - length);
                    }
                    else
                    {
                        index = 0;
                    }
                    viewElement.innerHTML = html.Insert(index, templatexml);
                }
            }
        }
#endif

        private string GenTemplateFieldHTML(string controlType, TBlockItem BlockItem, TBlockFieldItem BFI)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("<asp:TemplateField HeaderText=\"" + (string.IsNullOrEmpty(BFI.Description) ? BFI.DataField : BFI.Description) + "\" SortExpression=\"" + BFI.DataField + "\">");
            builder.AppendLine("<EditItemTemplate>");
            builder.AppendLine(GenTempateHTML("edit", controlType, BlockItem, BFI));
            builder.AppendLine("</EditItemTemplate>");
            builder.AppendLine("<FooterTemplate>");
            builder.AppendLine(GenTempateHTML("footer", controlType, BlockItem, BFI));
            builder.AppendLine("</FooterTemplate>");
            builder.AppendLine("<ItemTemplate>");
            builder.AppendLine(GenTempateHTML("item", controlType, BlockItem, BFI));
            builder.AppendLine("</ItemTemplate>");
            builder.AppendLine("</asp:TemplateField>");

            return builder.ToString();
        }

        private string GenDetailViewTemplateFieldHTML(string controlType, TBlockItem BlockItem, TBlockFieldItem BFI)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("<asp:TemplateField HeaderText=\"" + (string.IsNullOrEmpty(BFI.Description) ? BFI.DataField : BFI.Description) + "\" SortExpression=\"" + BFI.DataField + "\">");
            builder.AppendLine("<EditItemTemplate>");
            builder.AppendLine(GenTempateHTML("edit", controlType, BlockItem, BFI));
            builder.AppendLine("</EditItemTemplate>");
            builder.AppendLine("<InsertItemTemplate>");
            builder.AppendLine(GenTempateHTML("footer", controlType, BlockItem, BFI));
            builder.AppendLine("</InsertItemTemplate>");
            builder.AppendLine("<ItemTemplate>");
            builder.AppendLine(GenTempateHTML("item", controlType, BlockItem, BFI));
            builder.AppendLine("</ItemTemplate>");
            builder.AppendLine("</asp:TemplateField>");

            return builder.ToString();
        }

        private string GenTempateHTML(string template, string controlType, TBlockItem BlockItem, TBlockFieldItem BFI)
        {
            StringBuilder builder = new StringBuilder();
            String FormatStyle = this.FormatEditMask(BFI.EditMask);
            if (template == "edit")
            {
                switch (controlType)
                {
                    case "RefValBox":
                        IDbConnection conn = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, false);
                        InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
                        aInfoCommand.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
                        //aInfoCommand.Connection = conn;
                        String tableName = WzdUtils.RemoveQuote(this.FClientData.TableName, FClientData.DatabaseType);
                        aInfoCommand.CommandText = "Select * from COLDEF where TABLE_NAME = '" + tableName + "'";
                        IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
                        DataSet dsColdef = new DataSet();
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, dsColdef, this.FClientData.TableName);

                        DataSet aDataSet = new DataSet();
                        StringBuilder RefColumns = new StringBuilder("<Columns>");
                        aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL_D1 where REFVAL_NO = '{0}'", BFI.RefValNo);
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, aDataSet, BFI.RefValNo);
                        if (aDataSet != null && aDataSet.Tables.Count > 0 && aDataSet.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow DR in aDataSet.Tables[0].Rows)
                            {
                                RefColumns.Append(Environment.NewLine);
                                RefColumns.Append("<InfoLight:WebRefColumn ColumnName=\"" + DR["FIELD_NAME"].ToString() + "\" HeadText=\"" + DR["HEADER_TEXT"].ToString() + "\" Width=\"100\" />");
                            }
                            RefColumns.Append(Environment.NewLine);
                            RefColumns.Append("</Columns>");
                        }
                        else
                        {
                            RefColumns = new StringBuilder("");
                        }

                        String DataSourceID = GenWebDataSource(BFI, BlockItem.ProviderName, "RefVal", "").ID;
                        String refvalHTML = String.Format("<InfoLight:WebRefVal ID=\"{0}\" runat=\"server\" BindingValue='<%# Bind(\"{1}\"{5}) %>' " +
                                    "ButtonImageUrl=\"../Image/refval/RefVal.gif\" DataBindingField=\"{1}\" DataSourceID=\"{2}\" " +
                                    "DataTextField=\"{3}\" DataValueField=\"{4}\" ReadOnly=\"False\" ResxDataSet=\"\" " +
                                    "ResxFilePath=\"\" UseButtonImage=\"True\"> " +
                                     RefColumns.ToString() +
                                    "</InfoLight:WebRefVal>",
                                    "wrv" + BlockItem.ProviderName + BFI.DataField + "E",
                                    BFI.DataField,
                                    DataSourceID,
                                    FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString(),
                                    FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString(),
                                    FormatStyle
                                    );
                        builder.AppendLine(refvalHTML);
                        break;
                    case "ComboBox":
                        String comboHTML = string.Format("<InfoLight:WebDropDownList runat=\"server\" ID=\"{0}\" DataSourceID=\"{1}\" DataTextField=\"{2}\" DataValueField=\"{3}\" DataMember=\"{4}\" SelectedValue='<%# Bind(\"{5}\"{6}) %>'></InfoLight:WebDropDownList>",
                            "wdd" + BlockItem.ProviderName + BFI.DataField + "E",
                            GenWebDataSource(BFI, BFI.ComboTableName, "ComboBox", ""),
                            BFI.ComboTextField,
                            BFI.ComboValueField,
                            BFI.ComboTableName,
                            BFI.DataField,
                            FormatStyle);
                        builder.AppendLine(comboHTML);
                        break;
                    case "ValidateBox":
                        String validateHTML = String.Format("<InfoLight:WebValidateBox ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{3}) %>' ValidateField=\"{1}\" WebValidateID=\"{2}\"></InfoLight:WebValidateBox>",
                                    "wvb" + BlockItem.ProviderName + BFI.DataField + "E",
                                    BFI.DataField,
                                    "wv" + BlockItem.ProviderName,
                                    FormatStyle);
                        builder.AppendLine(validateHTML);
                        break;
                    case "CheckBox":
                        String checkHTML = String.Format("<asp:CheckBox ID=\"{0}\" runat=\"server\" Checked='<%# Bind(\"{1}\"{2}) %>'></asp:CheckBox>",
                                    "cb" + BlockItem.ProviderName + BFI.DataField + "E",
                                    BFI.DataField,
                                    FormatStyle);
                        builder.AppendLine(checkHTML);
                        break;
                    case "DateTimeBox":
                        string dtHTML = string.Format("<InfoLight:WebDateTimePicker runat=\"server\" UseButtonImage=\"True\" DateFormat=\"{0}\" DateTimeType=\"{1}\" Localize=\"False\" MinYear=\"1950\" MaxYear=\"2050\" ToolTip=\"{2}\" Width=\"100px\" ID=\"{3}\" {4}='<%# Bind(\"{5}\"{6}) %>'></InfoLight:WebDateTimePicker>",
                            "None",
                            (BFI.DataType == typeof(DateTime)) ? "DateTime" : "Varchar",
                            BFI.DataField,
                            "wdt" + BlockItem.ProviderName + BFI.DataField + "E",
                            (BFI.DataType == typeof(DateTime)) ? "Text" : "DateString",
                            BFI.DataField,
                            FormatStyle);
                        builder.AppendLine(dtHTML);
                        break;
                }
            }
            else if (template == "footer")
            {
                switch (controlType)
                {
                    case "RefValBox":
                        IDbConnection conn = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, false);
                        InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
                        aInfoCommand.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
                        //aInfoCommand.Connection = conn;
                        String tableName = WzdUtils.RemoveQuote(this.FClientData.TableName, FClientData.DatabaseType);
                        aInfoCommand.CommandText = "Select * from COLDEF where TABLE_NAME = '" + tableName + "'";
                        IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
                        DataSet dsColdef = new DataSet();
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, dsColdef, this.FClientData.TableName);

                        DataSet aDataSet = new DataSet();
                        StringBuilder RefColumns = new StringBuilder("<Columns>");
                        aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL_D1 where REFVAL_NO = '{0}'", BFI.RefValNo);
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, aDataSet, BFI.RefValNo);
                        if (aDataSet != null && aDataSet.Tables.Count > 0 && aDataSet.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow DR in aDataSet.Tables[0].Rows)
                            {
                                RefColumns.Append(Environment.NewLine);
                                RefColumns.Append("<InfoLight:WebRefColumn ColumnName=\"" + DR["FIELD_NAME"].ToString() + "\" HeadText=\"" + DR["HEADER_TEXT"].ToString() + "\" Width=\"100\" />");
                            }
                            RefColumns.Append(Environment.NewLine);
                            RefColumns.Append("</Columns>");
                        }
                        else
                        {
                            RefColumns = new StringBuilder("");
                        }

                        String DataSourceID = GenWebDataSource(BFI, BlockItem.ProviderName, "RefVal", "").ID;
                        String refvalHTML = String.Format("<InfoLight:WebRefVal ID=\"{0}\" runat=\"server\" BindingValue='<%# Bind(\"{1}\"{5}) %>' " +
                                    "ButtonImageUrl=\"../Image/refval/RefVal.gif\" DataBindingField=\"{1}\" DataSourceID=\"{2}\" " +
                                    "DataTextField=\"{3}\" DataValueField=\"{4}\" ReadOnly=\"False\" ResxDataSet=\"\" " +
                                    "ResxFilePath=\"\" UseButtonImage=\"True\"> " +
                                     RefColumns.ToString() +
                                    "</InfoLight:WebRefVal>",
                                    "wrv" + BlockItem.ProviderName + BFI.DataField + "F",
                                    BFI.DataField,
                                    DataSourceID,
                                    FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString(),
                                    FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString(),
                                    FormatStyle
                                    );
                        builder.AppendLine(refvalHTML);
                        break;
                    case "ComboBox":
                        string comboHTML = string.Format("<InfoLight:WebDropDownList runat=\"server\" ID=\"{0}\" DataSourceID=\"{1}\" DataTextField=\"{2}\" DataValueField=\"{3}\" DataMember=\"{4}\"></InfoLight:WebDropDownList>",
                            "wdd" + BlockItem.ProviderName + BFI.DataField + "F",
                            GenWebDataSource(BFI, BFI.ComboTableName, "ComboBox", ""),
                            BFI.ComboTextField,
                            BFI.ComboValueField,
                            BFI.ComboTableName);
                        builder.AppendLine(comboHTML);
                        break;
                    case "ValidateBox":
                        String validateHTML = String.Format("<InfoLight:WebValidateBox ID=\"{0}\" runat=\"server\" Text='<%# Bind(\"{1}\"{3}) %>' ValidateField=\"{1}\" WebValidateID=\"{2}\"></InfoLight:WebValidateBox>",
                                    "wvb" + BlockItem.ProviderName + BFI.DataField + "F",
                                    BFI.DataField,
                                    "wv" + BlockItem.ProviderName,
                                    FormatStyle);
                        builder.AppendLine(validateHTML);
                        break;
                    case "CheckBox":
                        String checkHTML = String.Format("<asp:CheckBox ID=\"{0}\" runat=\"server\" Checked='<%# Bind(\"{1}\"{2}) %>'></asp:CheckBox>",
                                    "cb" + BlockItem.ProviderName + BFI.DataField + "F",
                                    BFI.DataField,
                                    FormatStyle);
                        builder.AppendLine(checkHTML);
                        break;
                    case "DateTimeBox":
                        string dtHTML = string.Format("<InfoLight:WebDateTimePicker runat=\"server\" UseButtonImage=\"True\" DateFormat=\"{0}\" DateTimeType=\"{1}\" Localize=\"False\" MinYear=\"1950\" MaxYear=\"2050\" ToolTip=\"{2}\" Width=\"100px\" ID=\"{3}\"></InfoLight:WebDateTimePicker>",
                            "None",
                            (BFI.DataType == typeof(DateTime)) ? "DateTime" : "Varchar",
                            BFI.DataField,
                            "wdt" + BlockItem.ProviderName + BFI.DataField + "F");
                        builder.AppendLine(dtHTML);
                        break;
                }
            }
            else if (template == "item")
            {
                switch (controlType)
                {
                    case "RefValBox":
                        IDbConnection conn = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, false);
                        InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
                        aInfoCommand.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
                        //aInfoCommand.Connection = conn;
                        String tableName = WzdUtils.RemoveQuote(this.FClientData.TableName, FClientData.DatabaseType);
                        aInfoCommand.CommandText = "Select * from COLDEF where TABLE_NAME = '" + tableName + "'";
                        IDbDataAdapter DA = DBUtils.CreateDbDataAdapter(aInfoCommand);
                        DataSet dsColdef = new DataSet();
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, dsColdef, this.FClientData.TableName);

                        DataSet aDataSet = new DataSet();
                        StringBuilder RefColumns = new StringBuilder("<Columns>");
                        aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL_D1 where REFVAL_NO = '{0}'", BFI.RefValNo);
                        WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, aDataSet, BFI.RefValNo);
                        if (aDataSet != null && aDataSet.Tables.Count > 0 && aDataSet.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow DR in aDataSet.Tables[0].Rows)
                            {
                                RefColumns.Append(Environment.NewLine);
                                RefColumns.Append("<InfoLight:WebRefColumn ColumnName=\"" + DR["FIELD_NAME"].ToString() + "\" HeadText=\"" + DR["HEADER_TEXT"].ToString() + "\" Width=\"100\" />");
                            }
                            RefColumns.Append(Environment.NewLine);
                            RefColumns.Append("</Columns>");
                        }
                        else
                        {
                            RefColumns = new StringBuilder("");
                        }

                        String DataSourceID = GenWebDataSource(BFI, BlockItem.ProviderName, "RefVal", "").ID;
                        String refvalHTML = String.Format("<InfoLight:WebRefVal ID=\"{0}\" runat=\"server\" BindingValue='<%# Bind(\"{1}\"{5}) %>' " +
                                    "ButtonImageUrl=\"../Image/refval/RefVal.gif\" DataBindingField=\"{1}\" DataSourceID=\"{2}\" " +
                                    "DataTextField=\"{3}\" DataValueField=\"{4}\" ReadOnly=\"True\" BorderStyle=\"None\" ResxDataSet=\"\" " +
                                    "ResxFilePath=\"\" UseButtonImage=\"True\" Width=\"100px\" BackColor=\"Transparent\"> " +
                                     RefColumns.ToString() +
                                    "</InfoLight:WebRefVal>",
                                    "wrv" + BlockItem.ProviderName + BFI.DataField + "E",
                                    BFI.DataField,
                                    DataSourceID,
                                    FSYS_REFVAL.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString(),
                                    FSYS_REFVAL.Tables[0].Rows[0]["VALUE_MEMBER"].ToString(),
                                    FormatStyle
                                    );
                        builder.AppendLine(refvalHTML);
                        break;
                    default:
                        string labelHTML = string.Format("<asp:Label runat=\"server\" ToolTip=\"{0}\" ID=\"{1}\" Text='<%# Bind(\"{2}\"{3}) %>'></asp:Label>",
                            BFI.DataField,
                            "l" + BlockItem.ProviderName + BFI.DataField,
                            BFI.DataField,
                            FormatStyle);
                        builder.AppendLine(labelHTML);
                        break;
                }
            }
            return builder.ToString();
        }

        //因为DD只有一个格式栏位，所以Web和Windows统一一种Format格式
        private String FormatEditMask(String editMask)
        {
            if (editMask != null && editMask != String.Empty && !editMask.StartsWith(","))
                editMask = ",\"{0:" + editMask + "}\"";
            return editMask;
        }

#if VS90
        /// <summary>
        /// 在page中插入Control
        /// </summary>
        /// <param name="pageElement">Page的Element</param>
        /// <param name="control">Control</param>
        private void InsertControl(WebDevPage.IHTMLElement pageElement, WebControl control)
        {
            if (pageElement != null)
            {
                string controlxml = GetControlXml(control);

                if (control is WebRefVal)
                {
                    int i = controlxml.IndexOf("runat=\"server\"");
                    controlxml = controlxml.Insert(i + 14, " Visible=\"False\" ");
                }
                if (controlxml.Length > 0)
                {
                    string html = pageElement.innerHTML;
                    int index = IndexOfEndTag(html, "form");
                    if (index != -1)
                    {
                        pageElement.innerHTML = html.Insert(index, controlxml);
                    }
                }
            }
        }
#endif

        /// <summary>
        /// 取得Control对应的xml
        /// </summary>
        /// <param name="control">Control</param>
        /// <returns>xml</returns>
        private string GetControlXml(WebControl control)
        {
            return GetControlXml(control, null, string.Empty, string.Empty);
        }

        /// <summary>
        /// 取得Control对应的xml
        /// </summary>
        /// <param name="control">Control</param>
        /// <param name="prop">绑定Control的属性</param>
        /// <param name="field">绑定的字段</param>
        /// <param name="format">绑定的格式</param>
        /// <returns>xml</returns>
        private string GetControlXml(WebControl control, PropertyInfo prop, string field, string format)
        {
            StringBuilder builder = new StringBuilder();
            if (control != null)
            {
                StringBuilder builderInnerHtml = new StringBuilder();
                Type controltype = control.GetType();
                if (controltype.Namespace == "Srvtools")
                {
                    builder.Append(string.Format("<{0}:{1} ID=\"{2}\" runat=\"server\" ", INFOLIGHTMARK, controltype.Name, control.ID));
                }
                else
                {
                    builder.Append(string.Format("<{0}:{1} ID=\"{2}\" runat=\"server\" ", "Asp", controltype.Name, control.ID));
                }
                if (prop != null)
                {
                    builder.Append(string.Format("{0}='<%# Bind(\"{1}\"", prop.Name, field, format));
                    if (!string.IsNullOrEmpty(format))
                    {
                        builder.Append(string.Format("{0}", format));
                    }
                    builder.Append(") %>' ");
                }

                PropertyInfo[] infos = controltype.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
                for (int i = 0; i < infos.Length; i++)
                {
                    if (prop == null || (prop != null && prop.Name != infos[i].Name))
                    {
                        if (!IsVisibilityHidden(infos[i]))
                        {
                            if (infos[i].PropertyType == typeof(string) || infos[i].PropertyType == typeof(int) || infos[i].PropertyType == typeof(bool)
                                || infos[i].PropertyType.BaseType == typeof(Enum))
                            {
                                object value = infos[i].GetValue(control, null);
                                object defaultvalue = GetDefaultValue(infos[i]);
                                if (infos[i].CanWrite && value != defaultvalue)
                                {
                                    builder.Append(string.Format("{0}=\"{1}\" ", infos[i].Name, value));
                                }
                            }
                            else if (infos[i].PropertyType.BaseType == typeof(InfoOwnerCollection))
                            {
                                string collectionxml = GetCollectionXml(infos[i], (InfoOwnerCollection)infos[i].GetValue(control, null));
                                if (collectionxml.Length > 0)
                                {
                                    builderInnerHtml.AppendLine(collectionxml);
                                }
                            }
                        }
                    }
                }
                builder.AppendLine(">");
                builder.Append(builderInnerHtml.ToString());
                if (controltype.Namespace == "Srvtools")
                {
                    builder.AppendLine(string.Format("</{0}:{1}>", INFOLIGHTMARK, controltype.Name));
                }
                else
                {
                    builder.AppendLine(string.Format("</{0}:{1}>", "Asp", controltype.Name));
                }
            }
            return builder.ToString();
        }

        /// <summary>
        /// 取得tag在html的最始位置，如&lt;form&gt;
        /// </summary>
        /// <param name="html">html</param>
        /// <param name="tag">tag</param>
        /// <returns>最始位置</returns>
        private int IndexOfBeginTag(string html, string tag)
        {
            Match mc = Regex.Match(html, string.Format(@"<{0}\s*>", tag));
            if (mc.Success)
            {
                return mc.Index;
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        /// 取得tag在html的最末位置，如&lt;/form&gt;
        /// </summary>
        /// <param name="html">html</param>
        /// <param name="tag">tag</param>
        /// <returns>最末位置</returns>
        private int IndexOfEndTag(string html, string tag)
        {
            int length;
            return IndexOfEndTag(html, tag, out length);
        }

        /// <summary>
        /// 取得tag在html的最末位置，如&lt;/form&gt;
        /// </summary>
        /// <param name="html">html</param>
        /// <param name="tag">tag</param>
        /// <param name="length">tag的长度</param>
        /// <returns>最末位置</returns>
        private int IndexOfEndTag(string html, string tag, out int length)
        {
            Match mc = Regex.Match(html, string.Format(@"</{0}\s*>", tag), RegexOptions.RightToLeft);
            if (mc.Success)
            {
                length = mc.Length;
                return mc.Index;
            }
            else
            {
                length = 0;
                return -1;
            }
        }

        private void RenameForm()
        {
            string Path = FPI.get_FileNames(0);
            Path = System.IO.Path.GetDirectoryName(Path);
            string NewName = FClientData.FormName + ".cs";
            string FileName = Path + "\\" + NewName;
            FPI.SaveAs(FileName);
            System.IO.File.Delete(Path + "\\Form1.cs");
            System.IO.File.Delete(Path + "\\Form1.Designer.cs");
            System.IO.File.Delete(Path + "\\Form1.resx");
        }

        private void UpdateDataSource(TBlockItem MainBlockItem, TBlockItem ViewBlockItem)
        {
            InfoNavigator navigator3 = FRootForm.Controls["infoNavigator1"] as InfoNavigator;
            if (navigator3 != null)
                navigator3.ViewBindingSource = MainBlockItem.BindingSource;

            FViewGrid.DataSource = MainBlockItem.BindingSource;
            TBlockFieldItem FieldItem;
            //???FViewGrid.Columns.Clear();
            DataGridViewColumn Column;
            int I, Index;
            for (I = 0; I < ViewBlockItem.BlockFieldItems.Count; I++)
            {
                FieldItem = ViewBlockItem.BlockFieldItems[I] as TBlockFieldItem;
                if (FieldItem.Description == "")
                    Index = FViewGrid.Columns.Add(FieldItem.DataField, FieldItem.DataField);
                else
                    Index = FViewGrid.Columns.Add(FieldItem.DataField, FieldItem.Description);
                Column = FViewGrid.Columns[Index];
                Column.DataPropertyName = FieldItem.DataField;
                if (Column.HeaderText.Trim() == "")
                    Column.HeaderText = FieldItem.DataField;
            }
        }

        [DllImport("kernel32.dll")]
        public extern static void Sleep(uint msec);

        private void WriteWebDataSourceHTML()
        {
            //if (FWebDataSourceList.Count == 0)
            //    return;
            String FileName = FDesignWindow.Document.FullName;
            FDesignWindow.Close(vsSaveChanges.vsSaveChangesYes);

#if VS90
#else
            String UpdateHTML = "";
            //WebNavigator.QueryFields
            WebNavigator navigator1 = FPage.FindControl("WebNavigator1") as WebNavigator;
            TBlockItem aBlockItem = null;
            TBlockItem bBlockItem = null;
            if (navigator1 != null)
            {
                if (FClientData.IsMasterDetailBaseForm())
                {
                    aBlockItem = FClientData.Blocks.FindItem("Master");
                    foreach (MWizard.TBlockItem var in FClientData.Blocks)
                    {
                        if (var.ParentItemName == aBlockItem.Name)
                            bBlockItem = var;
                    }
                }
                else
                    aBlockItem = FClientData.Blocks.FindItem("Main");


                foreach (WebQueryField QF in navigator1.QueryFields)
                {
                    if (QF.RefVal != null && QF.RefVal != "")
                    {
                        TBlockFieldItem aFieldItem = aBlockItem.BlockFieldItems.FindItem(QF.FieldName);

                        if (QF.Mode == "RefVal")
                        {
                            String DataSourceID = GenWebDataSource(aFieldItem, aBlockItem.TableName, "RefVal", "QF").ID;
                            InfoCommand aInfoCommand = new InfoCommand(FClientData.DatabaseType);
                            aInfoCommand.Connection = WzdUtils.AllocateConnection(FClientData.DatabaseName, FClientData.DatabaseType, true);
                            //aInfoCommand.Connection = FClientData.Owner.GlobalConnection;
                            IDbDataAdapter DA =  DBUtils.CreateDbDataAdapter(aInfoCommand);
                            DataSet aDataSet = new DataSet();
                            aInfoCommand.CommandText = String.Format("Select * from SYS_REFVAL where REFVAL_NO = '{0}'", aFieldItem.RefValNo);
                            WzdUtils.FillDataAdapter(FClientData.DatabaseType, DA, aDataSet, aFieldItem.RefValNo);

                            String S1 = String.Format("<InfoLight:WebRefVal ID=\"{0}\" runat=\"server\" BindingValue='<%# Bind(\"{1}\") %>' " +
                                "ButtonImageUrl=\"../Image/refval/RefVal.gif\" DataBindingField=\"{1}\" DataSourceID=\"{2}\" " +
                                "DataTextField=\"{3}\" DataValueField=\"{4}\" ReadOnly=\"False\" ResxDataSet=\"\" " +
                                "ResxFilePath=\"\" UseButtonImage=\"True\" Visible=\"False\">" +
                                "</InfoLight:WebRefVal>",
                                "wrv" + aBlockItem.TableName + aFieldItem.DataField + "QF",
                                aFieldItem.DataField,
                                DataSourceID,
                                aDataSet.Tables[0].Rows[0]["DISPLAY_MEMBER"].ToString(),
                                aDataSet.Tables[0].Rows[0]["VALUE_MEMBER"].ToString());
                            UpdateHTML = UpdateHTML + S1;
                        }

                        if (QF.Mode == "ComboBox")
                        {
                            String DataSourceID = GenWebDataSource(aFieldItem, aBlockItem.TableName, "ComboBox", "QF").ID;
                            String S2 = String.Format("<InfoLight:WebRefVal ID=\"{0}\" runat=\"server\" BindingValue='<%# Bind(\"{1}\") %>' " +
                                "ButtonImageUrl=\"../Image/refval/RefVal.gif\" DataBindingField=\"{1}\" DataSourceID=\"{2}\" " +
                                "DataTextField=\"{3}\" DataValueField=\"{4}\" ReadOnly=\"False\" ResxDataSet=\"\" " +
                                "ResxFilePath=\"\" UseButtonImage=\"True\" Visible=\"False\"> " +
                                "</InfoLight:WebRefVal>",
                                "wrv" + aBlockItem.TableName + aFieldItem.DataField + "QF",
                                aFieldItem.DataField,
                                DataSourceID,
                                aFieldItem.ComboTextField,
                                aFieldItem.ComboValueField);
                            UpdateHTML = UpdateHTML + S2;
                        }
                    }
                }
            }

            //WebDataSource
            foreach (WebDataSource aWebDataSource in FWebDataSourceList)
            {
                UpdateHTML = UpdateHTML + String.Format(
                    "<InfoLight:WebDataSource ID=\"{0}\" runat=\"server\" SelectAlias=\"{1}\" SelectCommand=\"{2}\">\n", 
                    aWebDataSource.ID, aWebDataSource.SelectAlias, aWebDataSource.SelectCommand);
                UpdateHTML = UpdateHTML + "</InfoLight:WebDataSource>\n";
            }

            //WebDefault
            foreach (WebDefault aDefault in FWebDefaultList)
            {
                if (aDefault.Fields.Count > 0)
                {
                    UpdateHTML = UpdateHTML + String.Format(
                        "<InfoLight:WebDefault ID=\"{0}\" runat=\"server\" DataMember=\"{1}\" DataSourceID=\"{2}\">\n",
                        aDefault.ID, aDefault.DataMember, aDefault.DataSourceID);
                    UpdateHTML = UpdateHTML + "   <Fields>\n";
                }
                foreach (DefaultFieldItem DFI in aDefault.Fields)
                {
                    UpdateHTML = UpdateHTML + String.Format(
                        "      <InfoLight:DefaultFieldItem FieldName=\"{0}\" DefaultValue=\"{1}\" />\n",
                        DFI.FieldName, DFI.DefaultValue);
                }
                if (aDefault.Fields.Count > 0)
                {
                    UpdateHTML = UpdateHTML + "   </Fields>\n";
                    UpdateHTML = UpdateHTML + "</InfoLight:WebDefault>\n";
                }
            }

            //WebValidate
            foreach (WebValidate aValidate in FWebValidateList)
            {
                if (aValidate.Fields.Count > 0)
                {
                    UpdateHTML = UpdateHTML + String.Format(
                        "<InfoLight:WebValidate ID=\"{0}\" runat=\"server\" DataMember=\"{1}\" DataSourceID=\"{2}\" " +
                        "DuplicateCheck=\"False\" DuplicateCheckMode=\"ByLocal\" ForeColor=\"Red\" ValidateChar=\"*\" " +
                        "ValidateColor=\"Red\" ValidateStyle=\"ShowLable\">\n", aValidate.ID, aValidate.DataMember,
                        aValidate.DataSourceID);
                    UpdateHTML = UpdateHTML + "   <Fields>\n";
                }
                foreach (ValidateFieldItem VFI in aValidate.Fields)
                {
                    String ValidateLabelLink = "";
                    if (FClientData.BaseFormName == "WSingle1" || FClientData.BaseFormName == "WSingle2" || FClientData.BaseFormName == "WMasterDetail1" ||
                        FClientData.BaseFormName == "WMasterDetail3" || FClientData.BaseFormName == "VBWebCMasterDetail_FG")
                    {
                        ValidateLabelLink = " ValidateLabelLink=\"Caption" + VFI.FieldName + "\"";
                    }
                    UpdateHTML = UpdateHTML + String.Format(
                        "<InfoLight:ValidateFieldItem FieldName=\"{0}\" CheckNull=\"{1}\"{2}></InfoLight:ValidateFieldItem>\n",
                        VFI.FieldName, VFI.CheckNull.ToString(), ValidateLabelLink);
                }
                if (aValidate.Fields.Count > 0)
                {
                    UpdateHTML = UpdateHTML + "   </Fields>\n";
                    UpdateHTML = UpdateHTML + "</InfoLight:WebValidate>\n<br />";
                }
            }


            //Start Update Process
            String ReplaceTag = "<InfoLight:WebNavigator ID=";
            if (FClientData.BaseFormName.CompareTo("WSingle1") == 0 || FClientData.BaseFormName.CompareTo("WQuery") == 0)
                ReplaceTag = "<InfoLight:WebDataSource ID=";

            //String ReplaceTag = "<InfoLight:WebNavigator";
            //if (FClientData.BaseFormName == "WSingle1")
            //    ReplaceTag = "<InfoLight:WebDataSource";
            UpdateHTML = UpdateHTML + ReplaceTag;
            System.IO.StreamReader SR = new System.IO.StreamReader(FileName, Encoding.Default);
            String Context = SR.ReadToEnd();
            SR.Close();
            Context = Context.Replace(ReplaceTag, UpdateHTML);

            //WebRefVal
            foreach (WebRefVal aWebRefVal in FWebRefValList)
            {
                String EditMask = String.Empty;
                if (aBlockItem != null && aBlockItem.BlockFieldItems.FindItem(aWebRefVal.DataBindingField) != null)
                    EditMask = FormatEditMask(aBlockItem.BlockFieldItems.FindItem(aWebRefVal.DataBindingField).EditMask);
                if (bBlockItem != null && bBlockItem.BlockFieldItems.FindItem(aWebRefVal.DataBindingField) != null)
                    EditMask = FormatEditMask(bBlockItem.BlockFieldItems.FindItem(aWebRefVal.DataBindingField).EditMask);

                String newWebRefValID = aWebRefVal.ID.Remove(aWebRefVal.ID.LastIndexOf("GridView"));
                Context = Context.Replace(" ID=\"" + aWebRefVal.ID + "\"", String.Format("{0}\" BindingValue='<%# Bind(\"{1}\"{2}) %>'",
                    " ID=\"" + newWebRefValID, aWebRefVal.DataBindingField, EditMask));
            }

            //WebDropDownList
            foreach (MyWebDropDownList aWebDropDownList in FMyWebDropDownList)
            {
                String EditMask = String.Empty;
                if (aBlockItem != null && aBlockItem.BlockFieldItems.FindItem(aWebDropDownList.BindingField) != null)
                    EditMask = FormatEditMask(aBlockItem.BlockFieldItems.FindItem(aWebDropDownList.BindingField).EditMask);
                if (bBlockItem != null && bBlockItem.BlockFieldItems.FindItem(aWebDropDownList.BindingField) != null)
                    EditMask = FormatEditMask(bBlockItem.BlockFieldItems.FindItem(aWebDropDownList.BindingField).EditMask);

                String newWebDropDownListID = aWebDropDownList.WebDropDownList.ID.Remove(aWebDropDownList.WebDropDownList.ID.LastIndexOf("GridView"));
                Context = Context.Replace(aWebDropDownList.WebDropDownList.ID + "\"", String.Format("{0}\" SelectedValue='<%# Bind(\"{1}\"{2}) %>'",
                    newWebDropDownListID, aWebDropDownList.BindingField, EditMask));
            }

            //WebDateTimePicker
            foreach (WebDateTimePicker aDateTimePicker in FWebDateTimePickerList)
            {
                String SS = "";
                String EditMask = String.Empty;
                if (aBlockItem != null && aBlockItem.BlockFieldItems.FindItem(aDateTimePicker.ToolTip) != null)
                    EditMask = FormatEditMask(aBlockItem.BlockFieldItems.FindItem(aDateTimePicker.ToolTip).EditMask);
                if (bBlockItem != null && bBlockItem.BlockFieldItems.FindItem(aDateTimePicker.ToolTip) != null)
                    EditMask = FormatEditMask(bBlockItem.BlockFieldItems.FindItem(aDateTimePicker.ToolTip).EditMask);

                String newDateTimePickerID = aDateTimePicker.ID.Remove(aDateTimePicker.ID.LastIndexOf("GridView"));
                if (aDateTimePicker.DateTimeType == dateTimeType.DateTime)
                    SS = String.Format(" ID=\"{0}\" Text='<%# Bind(\"{1}\"{2}) %>'",
                                        newDateTimePickerID, aDateTimePicker.ToolTip, EditMask);
                else if (aDateTimePicker.DateTimeType == dateTimeType.VarChar)
                    SS = String.Format(" ID=\"{0}\" DateString='<%# Bind(\"{1}\"{2}) %>'",
                                        newDateTimePickerID, aDateTimePicker.ToolTip, EditMask);
                Context = Context.Replace(" ID=\"" + aDateTimePicker.ID + "\"", SS);
            }

            //WebValidateBox
            foreach (WebValidateBox aValidateBox in FWebValidateBoxList)
            {
                String EditMask = String.Empty;
                if (aBlockItem != null && aBlockItem.BlockFieldItems.FindItem(aValidateBox.ValidateField) != null)
                    EditMask = FormatEditMask(aBlockItem.BlockFieldItems.FindItem(aValidateBox.ValidateField).EditMask);
                if (bBlockItem != null && bBlockItem.BlockFieldItems.FindItem(aValidateBox.ValidateField) != null)
                    EditMask = FormatEditMask(bBlockItem.BlockFieldItems.FindItem(aValidateBox.ValidateField).EditMask);

                String newValidateBoxID = aValidateBox.ID.Remove(aValidateBox.ID.LastIndexOf("GridView"));
                String SSS = String.Format(" ID=\"{0}\" Text='<%# Bind(\"{1}\"{2}) %>'",
                    newValidateBoxID, aValidateBox.ValidateField, EditMask);
                Context = Context.Replace(" ID=\"" + aValidateBox.ID + "\"", SSS);
            }

            //Label
            foreach (System.Web.UI.WebControls.Label aLabel in FLabelList)
            {
                String EditMask = String.Empty;
                if (aBlockItem != null && aBlockItem.BlockFieldItems.FindItem(aLabel.ToolTip) != null)
                    EditMask = FormatEditMask(aBlockItem.BlockFieldItems.FindItem(aLabel.ToolTip).EditMask);
                if (bBlockItem != null && bBlockItem.BlockFieldItems.FindItem(aLabel.ToolTip) != null)
                    EditMask = FormatEditMask(bBlockItem.BlockFieldItems.FindItem(aLabel.ToolTip).EditMask);

                String newLabelID = aLabel.ID.Remove(aLabel.ID.LastIndexOf("GridView"));
                String S4 = String.Format("{0}\" Text='<%# Bind(\"{1}\"{2}) %>'",
                    newLabelID, aLabel.ToolTip, EditMask);
                Context = Context.Replace(aLabel.ID + "\"", S4);
            }

            //Page Title
            Context = Context.Replace("<title>Untitled Page</title>", "<title>" + FClientData.FormTitle + "</title>");
            
            System.IO.FileStream Filefs = new System.IO.FileStream(FileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
            System.IO.StreamWriter SW = new System.IO.StreamWriter(Filefs, Encoding.Default);
            SW.Write(Context);
            SW.Close();
            Filefs.Close();
#endif
            //FDesignWindow = FPI.Open("{00000000-0000-0000-0000-000000000000}");
            //FDesignWindow.Activate();
            FDesignWindow = FPI.Open("{7651A702-06E5-11D1-8EBD-00A0C90F26EA}");
            FDesignWindow.Activate();
        }

        public void GenWebClientModule()
        {
            GenFolder();
            GetForm();
            GetDesignerHost();
#if VS90
#else
  
            DesignerTransaction transaction1 = FDesignerHost.CreateTransaction();
#endif
            try
            {
                GenDataSet();
                SetupWebDataSource();
                GenWebBlock();
                WriteWebDataSourceHTML();
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message);
                return;
            }
            finally
            {
#if VS90
                FDesignWindow.Activate();



                bool b = FDesignerDocument.execCommand("Refresh", true, "");
#else
                transaction1.Commit();
#endif
            }
            //RenameForm();
            //FPI.Save(FPI.get_FileNames(0));
            //GlobalWindow.Close(vsSaveChanges.vsSaveChangesYes);
            FProject.Save(FProject.FullName);
            //FDTE2.Solution.SolutionBuild.BuildProject(FDTE2.Solution.SolutionBuild.ActiveConfiguration.Name,
            //    FProject.FullName, true);
        }
    }
 }

//常数 值 说明 
//vsViewKindAny {FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF} 任何视图。确定是否在任何上下文中打开项。仅适用于 IsOpen 属性。 
//vsViewKindCode {7651A701-06E5-11D1-8EBD-00A0C90F26EA} “代码”视图。 
//vsViewKindDebugging {7651A700-06E5-11D1-8EBD-00A0C90F26EA} “调试器”视图。 
//vsViewKindDesigner {7651A702-06E5-11D1-8EBD-00A0C90F26EA} “设计器”视图。 
//vsViewKindPrimary {00000000-0000-0000-0000-000000000000} “主”视图。即，项的默认视图。 
//vsViewKindTextView {7651A703-06E5-11D1-8EBD-00A0C90F26EA} “正文”视图。 
